stream api collect()使用map的个人类单词intsead

cgyqldqp  于 2021-07-14  发布在  Java
关注(0)|答案(2)|浏览(384)

如何将Map转换为包含单词及其频率的类单词

  1. List<Word>

或者我必须创造类似的

  1. Map<String, List<Word>> wordFreq

我避免使用一些简洁的方法

  1. public class Word implements Comparable<Word> {
  2. private String content;
  3. private int frequency;
  4. }
  1. class CONTAINER {
  2. public static void main(String[] args) {
  3. StringBuilder userWords = new StringBuilder();
  4. userWords.append("some sequence of words");
  5. Map<String, Long> wordFreq = Stream.of(userWords.toString().split(" ")).parallel()
  6. .collect(Collectors.groupingBy(String::toString, Collectors.counting()));
  7. List<Word> words = new ArrayList<>();
  8. for (Map.Entry<String, Long> a : wordFreq.entrySet()) {
  9. words.add(new Word(a.getKey(), Math.toIntExact(a.getValue())));
  10. }
  11. words.forEach(s -> System.out.println(s.getContent() + " : " + s.getFrequency()));
  12. }
  13. }
eiee3dmh

eiee3dmh1#

Map上有一个方便的方法:

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

r1zk6ea12#

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

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

相关问题