
流使用介绍:
计算结构:
副作用:
示例1:有副作用的代码
map<string, long> freq = new hashmap<>();
try (stream<string> words = new scanner(file).tokens()) {
words.foreach(word -> {
freq.merge(word.tolowercase(), 1l, long::sum);
});
}
问题:这段代码使用foreach来修改外部状态(freq)。它是迭代的并且不利用流。
示例2:无副作用的代码
map<string, long> freq;
try (stream<string> words = new scanner(file).tokens()) {
freq = words.collect(collectors.groupingby(string::tolowercase, collectors.counting()));
}
解决方案: 使用 collectors.groupingby 收集器创建频率表,而不改变外部状态。更短、更清晰、更高效。
流api的占用:
收藏家:
示例 3:提取最常见的十个单词的列表
list<string> topten = freq.entryset().stream()
.sorted(map.entry.<string, long>comparingbyvalue().reversed())
.limit(10)
.map(map.entry::getkey)
.collect(collectors.tolist());
说明:
收集器 api 的复杂性:
地图和收集攻略:
示例4:使用带有合并功能的tomap
map<string, long> freq;
try (stream<string> words = new scanner(file).tokens()) {
freq = words.collect(collectors.tomap(
string::tolowercase,
word -> 1l,
long::sum
));
}
说明:
示例 5:按艺术家对专辑进行分组并查找最畅销的专辑
map<artist, album> topalbums = albums.stream()
.collect(collectors.tomap(
album::getartist,
function.identity(),
binaryoperator.maxby(comparator.comparing(album::sales))
));
说明:
字符串集合:
collectors.joining 使用可选分隔符连接字符串。
示例 6:使用分隔符连接字符串
String result = Stream.of("came", "saw", "conquered")
.collect(Collectors.joining(", ", "[", "]"));
说明:
结论:
以上就是Item 优先选择流中没有副作用的函数的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号