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

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

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

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()));
  }
}
eiee3dmh

eiee3dmh1#

Map上有一个方便的方法:

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))))
r1zk6ea1

r1zk6ea12#

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

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

相关问题