简体   繁体   English

如何使用Stream API在Java 8中编写以下代码?

[英]How do I write below code in Java 8 using Stream API?

Is there any way to write the following code using Stream s? 有什么方法可以使用Stream编写以下代码?

public Map<String, Integer> process() {
    List<String> words = Arrays.asList(message.toLowerCase().split("[?.\\s]+"));
    Map<String, Integer> countMap = new HashMap<>();

    for (String word : words) {
        if (word.length() > 2) {
            Integer count = countMap.getOrDefault(word, 0);
            countMap.put(word, count + 1);
        }
    }
    return countMap;
}

Start out with 从开始

Pattern.compile("[?.\\s]+").splitAsStream(message.toLowerCase())

if you can live with a long result, stick with Ravindra's solution, if you need int, use Eran's counter. 如果可以长期有效,请坚持使用Ravindra的解决方案,如果需要使用int,请使用Eran的计数器。

So either: 所以:

Map<String, Long> r = Pattern.compile("[?.\\s]+").splitAsStream(message.toLowerCase())
    .filter(w -> w.length() > 2)
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

or 要么

Map<String, Integer> r = Pattern.compile("[?.\\s]+").splitAsStream(message.toLowerCase())
    .filter(w -> w.length() > 2)
    .collect(Collectors.toMap(Function.identity(), w -> 1, Integer::sum));

or (after the comment below) (even better) 或(在下面的评论之后)(甚至更好)

Map<String, Integer> r = Pattern.compile("[?.\\s]+").splitAsStream(message.toLowerCase())
    .filter(w -> w.length() > 2)
    .collect(Collectors.groupingBy(Function.identity(), Collectors.summingInt(x -> 1)));

You can use Collectors.toMap to generate the Map : 您可以使用Collectors.toMap生成Map

Map<String, Integer> countMap =
    words.stream()
         .filter(word -> word.length() > 2)
         .collect(Collectors.toMap(Function.identity(),w -> 1, Integer::sum));

Of course you can skip Arrays.asList and create a Stream directly from the array: 当然,您可以跳过Arrays.asList并直接从数组创建Stream

Map<String, Integer> countMap =
    Arrays.stream (message.toLowerCase().split("[?.\\s]+"))
          .filter(word -> word.length() > 2)
          .collect(Collectors.toMap(Function.identity(),w -> 1, Integer::sum));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM