Java中流式分割字符串

3
我有一个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));

现在我想要拆分列表,以便获得以下输出: 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());

输出:惠普&&宏碁&&戴尔

有人能帮忙吗?谢谢!


你想要**合并(join),而不是分割(split)**。合并 = 取几个部分并构造成一个字符串。分割 = 取一个字符串并提取出几个部分。 - JB Nizet
6个回答

3
首先,split()操作并非必要。虽然您可以将所有部分分割然后像那样将它们拼接在一起,但使用replacereplaceAll调用要简单得多。
其次,reduce操作不会很高效,因为它创建了许多中间的StringStringBuilder。相反,您应该使用更高效的String连接Collector:
 String temp = list.stream()
              .map(x -> x.name.replace(" ", "-"))
              .collect(Collectors.joining("&&"));

2
你写的第二个 map 操作保留了第一个单词。
相反,你可以这样做:
  1. Replace the spaces (\\s as regex) by a -

    Optional<String> temp = list.stream()
                                .map(x -> x.name)
                                .map(x -> x.replaceAll("\\s", "-"))
                                .reduce((str1, str2) -> str1 + "&&" + str2);
    
  2. Split on space, and then join with the -

    Optional<String> temp  = list.stream()
                                 .map(x -> x.name)
                                 .map(x -> String.join("-", x.split("\\s")))
                                 .reduce((str1, str2) -> str1 + "&&" + str2);
    

1
尝试在字符串流上使用收集器:
.collect(Collectors.joining("&&"))

0
Optional<String> temp = list.stream().map(x -> x.name)
                  .map(x -> x.replaceAll("\\s", "-"))
                  .reduce((str1, str2) -> str1 + "&&" + str2);

0
一种简单的方法是重写 Product 类中的 toString() 方法,以按所需格式打印名称,然后通过迭代列表将每个结果连接到较长的字符串上。

0

你需要将这部分 map(x -> x.split(" ")) 替换为 map(x -> x.replaceAll("\\s","-"))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接