我有一個 POJO 類產(chǎn)品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));現(xiàn)在我想拆分列表以獲得輸出 HP-Laptop-Speakers&&Acer-Keyboard&&Dell-Mouse.我只想要一個流中的班輪。到目前為止,我已經(jīng)設(shè)法得到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有人可以幫我嗎。提前致謝。
3 回答

largeQ
TA貢獻2039條經(jīng)驗 獲得超8個贊
首先,split()不需要手術(shù)。雖然您可以拆分所有部分,然后像這樣將它們連接在一起,但使用replaceorreplaceAll調(diào)用要簡單得多。
其次,reduce 操作的效率不會很高,因為它會創(chuàng)建大量的中介Strings 和StringBuilders。相反,您應(yīng)該使用String更高效的加入收集器:
String temp = list.stream()
.map(x -> x.name.replace(" ", "-"))
.collect(Collectors.joining("&&"));
添加回答
舉報
0/150
提交
取消