Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string in a stream Java

I have a POJO class Product

List<Product> list = new ArrayList<>();
list.add(new Product(1, "HP Laptop Speakers", 25000));
list.add(new Product(30, "Acer Keyboard", 300));
list.add(new Product(2, "Dell Mouse", 150));

Now I want to split the list to get output as HP-Laptop-Speakers&&Acer-Keyboard&&Dell-Mouse.

I just want a single liner in stream. So far I have managed to get

Optional<String> temp = list.stream().
                   map(x -> x.name).
                   map(x -> x.split(" ")[0]).
                   reduce((str1, str2) -> str1 + "&&" + str2);
System.out.println(temp.get());

Output: HP&&Acer&&Dell

Can someone help me out. Thanks in advance.

like image 410
Harshal Avatar asked Dec 03 '25 09:12

Harshal


1 Answers

First, the split() operation is not necessary. While you could split all the pieces and then join them together like that, it is far simpler to use a replace or replaceAll call instead.

Secondly, the reduce operation will not be very efficient since it is creating lots of intermediary Strings and StringBuilders. Instead, you should use the String joining Collector, which is more efficient:

 String temp = list.stream()
              .map(x -> x.name.replace(" ", "-"))
              .collect(Collectors.joining("&&"));
like image 199
Patrick Parker Avatar answered Dec 05 '25 00:12

Patrick Parker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!