我有一个POJO类产品
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));
现在我想拆分列表以获得HP-Laptop-Speakers&&Acer-Keyboard&&Dell-Mouse.
格式的输出
我只想要一个单独的班轮。到目前为止,我已经设法
Optional<String> temp = list.stream().
map(x -> x.name).
map(x -> x.split(" ")[0]).
reduce((str1, str2) -> str1 + "&&" + str2);
System.out.println(temp.get());
输出:HP&&Acer&&Dell
谁能帮帮我。提前谢谢。
发布于 2018-08-09 02:42:00
首先,split()
操作不是必需的。虽然您可以拆分所有部分,然后像这样将它们连接在一起,但使用replace
或replaceAll
调用要简单得多。
其次,reduce操作效率不高,因为它创建了大量的中间String
和StringBuilder
。相反,您应该使用String
加入收集器,它的效率更高:
String temp = list.stream()
.map(x -> x.name.replace(" ", "-"))
.collect(Collectors.joining("&&"));
发布于 2018-08-09 02:29:14
尝试在字符串流上使用收集器:
.collect(Collectors.joining("&&"))
发布于 2018-08-09 02:29:20
一种简单的方法是覆盖Product类中的toString()方法,按照您想要的格式打印名称,然后遍历列表,将每个结果连接到一个更长的字符串上。
https://stackoverflow.com/questions/51753372
复制相似问题