JDK8.0 流stream 基本操作

Stream当成一个高级版本的Iterator。原始版本的Iterator,用户只能一个一个的遍历元素并对其执行某些操作;高级版本的Stream,用户只要给出需要对其包含的元素执行什么操作,比如“过滤掉长度大于10的字符串”、“获取每个字符串的首字母”等,具体这些操作如何应用到每个元素上

一.初始化
1.value
Stream<String> stream = Stream. of ( "a" , "b" , "c" );
2.array
String [] strArray = new String[] { "a" , "b" , "c" };
stream = Stream. of (strArray);
stream = Arrays. stream (strArray);
3.list
List<String> list = Arrays. asList (strArray);
stream = list.stream();
二.流转换
1.转array
String[] strArray1 = stream.toArray(String[]::new);
2.转list
List <String> list = stream.collect(Collectors. toList ());
3.转String
String str = stream.collect(Collectors. joining ()).toString();
三.操作(创建stream-->转换stream-->聚合)
1.map
List<String> list = stream.map(String ::toUpperCase). collect(Collectors. toList ());
2.filter
String a = stream.filter(l->l.equals( "a" )). collect(Collectors. joining ());
3.forEach
stream.forEach(System. out ::println);
personList2 .forEach(a->System. out .println(a.getName()));
4.peek对每个元素操作
Stream. of ( "one" , "two" , "three" , "four" )
.peek(e -> System. out .println( "Filtered value: " + e))
.map(String::toUpperCase)
.peek(e -> System. out .println( "Mapped value: " + e))
.collect(Collectors. toList ());
5.reduce: 主要作用是把 Stream 元素组合起来
// 求最小值, minValue = -3.0
double minValue = Stream. of (- 1.5 , 1.0 , - 3.0 , - 2.0 ).reduce(Double. MAX_VALUE , Double:: min );
// 求和, sumValue = 10, 有起始值
int sumValue = Stream. of ( 1 , 2 , 3 , 4 ).reduce( 0 , Integer:: sum );
6. limit/skip
limit 返回 Stream 的前面 n 个元素;skip 则是扔掉前 n 个元素
7.sorted
List<Person> personList2 = list.stream().limit( 2 ).sorted((p1, p2) -> p1.getName().compareTo(p2.getName())).collect(Collectors. toList ());
personList2.forEach(a->System. out .println(a.getName()));
其他操作
map (mapToInt, flatMap 等)、 filter、 distinct、 sorted、 peek、 limit、 skip、 parallel、 sequential、 unordered
forEach、 forEachOrdered、 toArray、 reduce、 collect、 min、 max、 count、 anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 iterator
anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 limit


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值