Java——》Stream示例
发布日期:2021-09-14 23:18:27 浏览次数:8 分类:技术文章

本文共 12277 字,大约阅读时间需要 40 分钟。

版权声明:本文为博主原创文章,无需授权即可转载,甚至无需保留以上版权声明,转载时请务必注明作者。

https://blog.csdn.net/weixin_43453386/article/details/106419374

一、简介

操作 方法
拼接 joining()
集合 toList()
toSet()
toMap()
toCollection()
映射 mapping()
map()
分组 groupingBy()
partitioningBy()
计算 sum()
max()
min()
average()
reducing()
summingInt()
sum()
过滤 filter()
消费 peek()
排序 sorted()
匹配 anyMatch()
allMatch()
noneMatch()

二、示例

import lombok.Data;import java.util.*;import java.util.concurrent.CopyOnWriteArrayList;import java.util.function.Function;import java.util.stream.Collectors;public class StreamTest {
//对象集合 public static List
userList = Arrays.asList( new User(1, "张三", 12, "女"), new User(2, "李四", 21, "男"), new User(3, "王五", 32, "男"), new User(4, "王五", 32, "男")); //字符串集合 public static List
strList = Arrays.asList("a1", "b1", "a2"); //数字集合 public static List
intList = Arrays.asList(1, 2, 3,3,4); public static void main(String[] args) {
//拼接的字符 String delimiter = " , "; String prefix = "Start--"; String suffix = "--End"; System.out.println("默认拼接:"+ strList.stream() .collect(Collectors.joining())); System.out.println("逗号拼接:"+String.join(delimiter, strList)); System.out.println("逗号拼接:"+strList.stream() .collect(Collectors.joining(delimiter))); System.out.println("逗号拼接:"+userList.stream().map(e->e.getName()).collect(Collectors.joining(delimiter))); System.out.println("开头、中间、结尾,都拼接:"+strList.stream() .collect(Collectors.joining(delimiter, prefix, suffix))); System.out.println("/******************************************************************************************************/"); System.out.println("把所有的User的name,放入List
:"+userList.stream().map(User::getName).collect(Collectors.toList())); System.out.println("把所有的User的name,去重,放入List
:"+userList.stream().map(User::getName).distinct().collect(Collectors.toList())); System.out.println("/******************************************************************************************************/"); //set自动去重,没有顺序 System.out.println("把所有的User的name,放入Set
:"+ userList.stream().map(User::getName).collect(Collectors.toSet())); System.out.println("/******************************************************************************************************/"); /** * 要求:key为id,value为User * 注意:toMap时,一定要注意key是否重复,当前key不重复 * 结果:{1=User(id=1, name=张三, age=12, sex=女), 2=User(id=2, name=李四, age=21, sex=男), 3=User(id=3, name=王五, age=32, sex=男), 4=User(id=4, name=王五, age=32, sex=男)} * 异常:如果key重复,就会报错java.lang.IllegalStateException: Duplicate key */ System.out.println("key为id,value为User,当前key不重复:"+userList.stream().collect(Collectors.toMap(User::getId, Function.identity()))); System.out.println("key为id,value为User,当前key不重复:"+userList.stream().collect(Collectors.toMap(User::getId, user->user))); System.out.println("key为(id+sex),value为name,当前key不重复:"+userList.stream().collect(Collectors.toMap(e->e.getId().toString().concat("-").concat(e.getSex()), e->e.getName()))); System.out.println("key为id,value为(name+sex),当前key不重复:"+userList.stream().collect(Collectors.toMap(e->e.getId().toString(), e->e.getName().toString().concat("-").concat(e.getSex())))); System.out.println("key为name,value为User,当前key重复,value以第1个为准:"+userList.stream().collect(Collectors.toMap(User::getName,Function.identity(),(t1, t2) -> t1))); System.out.println("key为name,value为User,当前key重复,value以第2个为准:"+userList.stream().collect(Collectors.toMap(User::getName,Function.identity(),(t1, t2) -> t2))); System.out.println("/******************************************************************************************************/"); System.out.println("用LinkedList收集:"+intList.stream().collect(Collectors.toCollection(LinkedList::new)).toString()); System.out.println("用CopyOnWriteArrayList收集:"+intList.stream().collect(Collectors.toCollection(CopyOnWriteArrayList::new)).toString()); System.out.println("用TreeSet收集:"+intList.stream().collect(Collectors.toCollection(TreeSet::new)).toString()); System.out.println("/******************************************************************************************************/"); /** * 要求:按name分组,key为name,value为List
* 结果: key:李四 value:[User(id=2, name=李四, age=21, sex=男)] key:张三 value:[User(id=1, name=张三, age=12, sex=女)] key:王五 value:[User(id=3, name=王五, age=32, sex=男), User(id=4, name=王五, age=32, sex=男)] */ Map
> map = userList.stream().collect(Collectors.groupingBy(User::getName)); map.entrySet().forEach(e-> System.out.println("key:"+e.getKey()+"\n"+"value:"+e.getValue())); System.out.println("/******************************************************************************************************/"); /** * 要求:按sex分组,key为sex,value为Set
* 结果: key:女 value:[张三] key:男 value:[李四, 王五] */ Map
> map1 = userList.stream().collect(Collectors.groupingBy(User::getSex, Collectors.collectingAndThen( Collectors.toMap( e -> e, e -> e.getName() ), e -> e.values() .stream() .collect(Collectors.toSet()) ))); map1.entrySet().forEach(e-> System.out.println("key:"+e.getKey()+"\n"+"value:"+e.getValue())); System.out.println("/******************************************************************************************************/"); /** * 要求:按name分组,value.key为id,value.value为name * 注意:key是否重复,当前key不重复 * 结果: key:李四 value:{2=李四} key:张三 value:{1=张三} key:王五 value:{3=王五, 4=王五} */ Map
> map2 = userList.stream().collect(Collectors.groupingBy(User::getName,Collectors.toMap(User::getId, User::getName))); map2.entrySet().forEach(e-> System.out.println("key:"+e.getKey()+"\n"+"value:"+e.getValue())); System.out.println("/******************************************************************************************************/"); /** * 要求:按name分组,value.key为id,value.value为(name+sex) * 注意:key是否重复,当前key不重复 * 结果: key:李四 value:{2=李四-男} key:张三 value:{1=张三-女} key:王五 value:{3=王五-男, 4=王五-男} */ Map
> map3 = userList.stream().collect(Collectors.groupingBy(User::getName,Collectors.toMap(User::getId, e->e.getName().concat("-").concat(e.getSex())))); map3.entrySet().forEach(e-> System.out.println("key:"+e.getKey()+"\n"+"value:"+e.getValue())); System.out.println("/******************************************************************************************************/"); /** * 要求:按name分组,value.key为id,value.value为(name+sex) * 注意:key是否重复,当前key重复,以第1个为准 * 结果: key:李四 value:{2=李四-男} key:张三 value:{1=张三-女} key:王五 value:{3=王五-男, 4=王五-男} */ Map
> map4 = userList.stream().collect(Collectors.groupingBy(User::getName,Collectors.toMap(User::getId, e->e.getName().concat("-").concat(e.getSex()),(e1,e2)->e1))); map4.entrySet().forEach(e-> System.out.println("key:"+e.getKey()+"\n"+"value:"+e.getValue())); System.out.println("/******************************************************************************************************/"); /** * 要求:按sex分组,把同一组的name用逗号分割 * 结果: key:女 value:张三 key:男 value:王五,李四,王五 */ Map
map5 = userList.stream() .collect( Collectors.groupingBy( User::getSex, Collectors.collectingAndThen( Collectors.toMap( e -> e, e -> e.getName() ), e -> e.values() .stream() .collect(Collectors.joining(",")) ) )); map5.entrySet().forEach(e-> System.out.println("key:"+e.getKey()+"\n"+"value:"+e.getValue())); System.out.println("/******************************************************************************************************/"); /** * 要求:按奇偶数分组 * 结果: key:false value:[1, 3, 3] key:true value:[2, 4] */ Map
> map6 = intList.stream().collect(Collectors.groupingBy(item -> item % 2 == 0)); map6.entrySet().forEach(e-> System.out.println("key:"+e.getKey()+"\n"+"value:"+e.getValue())); System.out.println("/******************************************************************************************************/"); System.out.println("最大值:"+intList.stream().collect(Collectors.collectingAndThen(Collectors.maxBy((a, b) -> a - b), Optional::get)).toString()); System.out.println("/******************************************************************************************************/"); System.out.println("最小值:"+ intList.stream().collect(Collectors.collectingAndThen(Collectors.minBy((a, b) -> a - b), Optional::get)).toString()); System.out.println("/******************************************************************************************************/"); System.out.println("平均值:"+ intList.stream().collect(Collectors.averagingDouble(item -> item))); System.out.println("/******************************************************************************************************/"); System.out.println("求和一:"+userList.stream().collect(Collectors.summingInt(item -> item.getAge()))); System.out.println("求和二:"+userList.stream().map(User::getAge).reduce(0,Integer::sum)); System.out.println("求和三:"+userList.stream().mapToInt(User::getAge).sum()); System.out.println("/******************************************************************************************************/"); System.out.println("在每个name前面加上符号,再用逗号拼接:"+userList.stream().collect(Collectors.mapping(e -> "【".concat(e.getName()).concat("】"), Collectors.joining(",")))); System.out.println("/******************************************************************************************************/"); Map
collect = userList.stream().collect(Collectors.groupingBy(User::getSex, Collectors.summarizingInt(User::getAge))); IntSummaryStatistics statistics1 = collect.get("男"); IntSummaryStatistics statistics2 = collect.get("女"); System.out.println("【统计】和:"+statistics1.getSum()+","+"平均值:"+statistics1.getAverage()+","+"最大值:"+statistics1.getMax()+","+"最小值:"+statistics1.getMin()+","+"平均值:"+statistics1.getAverage()+","+"计数:"+statistics1.getCount()); System.out.println("【统计】和:"+statistics2.getSum()+","+"平均值:"+statistics2.getAverage()+","+"最大值:"+statistics2.getMax()+","+"最小值:"+statistics2.getMin()+","+"平均值:"+statistics2.getAverage()+","+"计数:"+statistics2.getCount()); System.out.println("/******************************************************************************************************/"); /** * intList:[1, 2, 3, 3, 4] * sum :是每次累计计算的结果 * b :Function的结果,也就是 x+1 的结果 * 结果 :18 * 过程 : 0+2 2+3 5+4 9+4 13+5 */ System.out.println("累计计算:"+intList.stream().collect(Collectors.reducing(0, x -> x + 1, (sum, b) -> { System.out.println(sum + "+" + b); return sum + b; }))); // 下面代码是对reducing函数功能实现的描述,用于理解reducing的功能 int sum = 0; for (Integer item : intList) { int b = item + 1; System.out.println(sum + "+" + b); sum = sum + b; } System.out.println("累计计算:"+sum); System.out.println("/******************************************************************************************************/"); System.out.println("过滤age>=21:"+userList.stream().filter(a -> a.getAge()>=21).map(e->e.getName()).collect(Collectors.toList())); System.out.println("过滤sex==男:"+userList.stream().filter(a -> "男".equals(a.getSex())).map(e->e.getName()).collect(Collectors.toList())); System.out.println("/******************************************************************************************************/"); /** * 要求:每个User的age,都扩大10位 * 结果: 1,张三,old age:12 1,张三,new age:120 User(id=1, name=张三, age=120, sex=女) */ userList.stream().peek(e->{ System.out.println(e.getId() +","+e.getName()+","+"old age:"+e.getAge()); e.setAge(e.getAge()*10); System.out.println(e.getId() +","+e.getName()+","+"new age:"+e.getAge()); }).forEach(System.out::println); System.out.println("/******************************************************************************************************/"); System.out.println("默认按照自然顺序进行排序:"+intList.stream().sorted().collect(Collectors.toList())); System.out.println("按照降序顺序进行排序:"+intList.stream().sorted((a,b)->b.compareTo(a)).collect(Collectors.toList())); System.out.println("/******************************************************************************************************/"); System.out.println("集合中是否任一元素匹配以'a'开头:"+strList.stream().anyMatch((s) -> s.startsWith("a"))); System.out.println("集合中是否所有元素匹配以'a'开头:"+strList.stream().allMatch((s) -> s.startsWith("a"))); System.out.println("集合中是否没有元素匹配以'd'开头:"+strList.stream().noneMatch((s) -> s.startsWith("a"))); }}@Dataclass User{ public Integer id; public String name; public Integer age; public String sex; public User(Integer id, String name, Integer age,String sex) { this.id = id; this.name = name; this.age = age; this.sex = sex; }}

转载地址:https://blog.csdn.net/weixin_43453386/article/details/106419374 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:读书有益——》告别自己
下一篇:SpringBoot——》异步执行:@EnableAsync、@Async

发表评论

最新留言

留言是一种美德,欢迎回访!
[***.207.175.100]2024年03月24日 08时06分29秒