Splitting strings in Java streams

I have a POJO 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 the output of HP laptop speakers & & Acer keyboard & & Dell mouse

I just want to use a single pad in the stream So far, I have succeeded

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 Thank you in advance

Solution

First, the split () operation is not required Although you can split all parts and connect them together, it is easier to use replace or replaceall calls

Secondly, the reduce operation is inefficient because it creates a large number of intermediate strings and StringBuilder Instead, you should use string to connect to the collector, which is more effective:

String temp = list.stream()
              .map(x -> x.name.replace(" ","-"))
              .collect(Collectors.joining("&&"));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>