Stream API collect() 使用 personal class Word 而不是 Map
Stream API collect() use personal class Word intsead of Map
我如何将我的地图转换为 class 包含单词及其频率的单词
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()));
}
}
您可以使用Stream.map(..)
方法。在你的情况下是:
List<Word> words = wordFreq.entrySet()
.stream()
.map(entry -> new Word(a.getKey(), Math.toIntExact(a.getValue())))
.collect(Collectors.toList());
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))))
我如何将我的地图转换为 class 包含单词及其频率的单词
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()));
}
}
您可以使用Stream.map(..)
方法。在你的情况下是:
List<Word> words = wordFreq.entrySet()
.stream()
.map(entry -> new Word(a.getKey(), Math.toIntExact(a.getValue())))
.collect(Collectors.toList());
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))))