【问题标题】:Stream API collect() use personal class Word intsead of MapStream API collect() 使用个人类 Word 而不是 Map
【发布时间】:2021-04-20 09:19:54
【问题描述】:

如何将我的地图转换为包含单词及其频率的 Word 类

List<Word> 

或者我必须创建类似的

Map<String, List<Word>> wordFreq 

为了简洁,我避免使用一些方法

public class Word implements Comparable<Word> {

    private String content;

    private int frequency;
}

class CONTAINER {
 public static void main(String[] args) {
 StringBuilder userWords = new StringBuilder();
userWords.append("some sequence of words");

Map<String, Long> wordFreq = Stream.of(userWords.toString().split(" ")).parallel()
                    .collect(Collectors.groupingBy(String::toString, Collectors.counting()));

            List<Word> words = new ArrayList<>();
            for (Map.Entry<String, Long> a : wordFreq.entrySet()) {
                words.add(new Word(a.getKey(), Math.toIntExact(a.getValue())));
            }
    words.forEach(s -> System.out.println(s.getContent() + " : " + s.getFrequency()));
  }
}

【问题讨论】:

    标签: java collections java-8 java-stream


    【解决方案1】:

    Map中有一个方便的方法forEach:

    List<Word> words = new ArrayList<>();
    Stream.of(userWords.toString().split(" "))
        .parallel()
        .collect(Collectors.groupingBy(String::toString, Collectors.counting()))
        .forEach((k, v) -> words.add(new Word(k, Math.toIntExact(v))))
    

    【讨论】:

      【解决方案2】:

      您可以使用Stream.map(..) 方法。你的情况是:

      List<Word> words = wordFreq.entrySet()
               .stream()
               .map(entry -> new Word(a.getKey(), Math.toIntExact(a.getValue())))
               .collect(Collectors.toList());
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-21
        • 2012-01-14
        • 2014-07-27
        • 2018-10-16
        • 2019-06-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多