欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 会展 > 集合常用Stream操作

集合常用Stream操作

2025/4/19 10:18:34 来源:https://blog.csdn.net/GM_115/article/details/147248593  浏览:    关键词:集合常用Stream操作

1、中间操作

filter()过滤

将流中的元素筛选出满足条件的元素

List<String> list = Arrays.asList("abc","test","demo","frse","fesfes");
list.stream().filter(s -> s.startsWith("f")).forEach(System.out::println);

map()映射转换

将流中的每个元素通过特定的函数转换为另一个流。

语法:<R> Stream<R> map(Function<? super T, ? extends R> mapper)

list.stream().map(String::toUpperCase).forEach(System.out::println);
//获取对象元素
userList.stream().map(User::getName).forEach(System.out::println);

distinct()去重

list.stream().distinct().forEach(System.out::println);

sorted()排序

list.stream().sorted().forEach(System.out::println);
list.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);

2、终端操作

foreach()遍历

list.stream().forEach(System.out::println);

collect()收集结果

List<String> upperList = list.stream().map(String::toUpperCase).collect(Collectors.toList());Set<String> set = list.stream().collect(Collectors.toSet());String joined = list.stream().collect(Collectors.joining(", "));

toArray()转为数组

String[] array = list.stream().toArray(String[]::new);

reduce()归约

Optional<String> reduced = list.stream().reduce((s1, s2) -> s1 + "#" + s2);int sum = numbers.stream().reduce(0, Integer::sum);

count()统计

long count = list.stream().count();

anyMatch()/allMatch()/noneMatch()  匹配检查

boolean anyStartsWithA = list.stream().anyMatch(s -> s.startsWith("a"));
boolean allStartsWithA = list.stream().allMatch(s -> s.startsWith("a"));
boolean noneStartsWithA = list.stream().noneMatch(s -> s.startsWith("a"));

findFirst()/findAny()查找元素

Optional<String> first = list.stream().findFirst();
Optional<String> any = list.stream().findAny();

3、Collectors工具类

toList()/toSet()/toCollection()

List<String> list = stream.collect(Collectors.toList());
Set<String> set = stream.collect(Collectors.toSet());
TreeSet<String> treeSet = stream.collect(Collectors.toCollection(TreeSet::new));
//转为map
Map<String, Integer> userMap = userList.stream().collect(Collectors.toMap(User::getName, User::getAge));

joining()字符串连接

String joined = stream.collect(Collectors.joining(", ", "[", "]"));

summarizingInt()/summarizingDouble()统计

IntSummaryStatistics stats = stream.collect(Collectors.summarizingInt(String::length));

groupingBy()分组

Map<Integer, List<String>> groupByLength = stream.collect(Collectors.groupingBy(String::length));Map<Integer, Long> countByLength = stream.collect(Collectors.groupingBy(String::length, Collectors.counting()));

mapping()下游收集器

Map<Integer, List<Character>> firstCharByLength = stream.collect(Collectors.groupingBy(String::length,Collectors.mapping(s -> s.charAt(0), Collectors.toList())));

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词