Stream流

一、Steam流的创建

Stream<Object> listStream = new ArrayList<>().stream(); //单列集合
Stream<Object> mapStream = new HashMap<>().keySet().stream();//双列集合
Stream<Object> arrayStream = Arrays.stream(new String[1]);//数组
Stream<Object> stream = Stream.of("a", "b");//零散数据

二、Stream流的中间方法

1.filter  过滤

List<String> list = new ArrayList<>();
Collections.addAll(list, "a", "a", "b", "c");
list.stream().filter(item -> item.equals("a")).forEach(System.out::println);// a  a

 结果:a a

2.limit 获取前几个元素

List<String> list = new ArrayList<>();
Collections.addAll(list, "a", "a", "b", "c");
list.stream().limit(3).forEach(System.out::println);//a a b

结果:a a b 

3.skip 跳过前几个元素

List<String> list = new ArrayList<>();
Collections.addAll(list, "a", "a", "b", "c");
list.stream().skip(3).forEach(System.out::println);//c

结果:c 

4.distinct 元素去重

List<String> list = new ArrayList<>();
Collections.addAll(list, "a", "a", "b", "c");
list.stream().distinct().forEach(System.out::println);//a b c

结果:a b c 

5.concat 将两个流合并

List<String> list1 = new ArrayList<>();
Collections.addAll(list1, "a", "b", "c");
List<String> list2 = new ArrayList<>();
Collections.addAll(list2,"d", "e", "f");
Stream.concat(list1.stream(), list2.stream()).forEach(System.out::println);//a b c d e f

结果:a b c d e f

6.map  转换数据类型返回新集合等操作

List<String> list = new ArrayList<>();
Collections.addAll(list, "a-1", "b-2", "c-3");
list.stream().map(item -> item.split("-")[1]).forEach(System.out::println);//1 2 3

结果:1 2 3

三、Stream流的终结方法

1、forEach遍历

2、count计算个数

3、toArray收集成数组

List<String> list = new ArrayList<>();
Collections.addAll(list, "a", "b", "c");

//forEach
list.stream().forEach(System.out::println); //a b c

//count
long count = list.stream().count();
System.out.println(count); //3

//toArray
String[] strings = list.stream().toArray(item -> new String[item]);
System.out.println(Arrays.toString(strings));//[a, b, c]

结果:a b c

           3

           [a, b, c] 

 4、collect收集成集合(List Set Map)

List<String> list = new ArrayList<>();
Collections.addAll(list, "a", "b", "c");
//List
List<String> streamList = list.stream().collect(Collectors.toList());
System.out.println(streamList);//[a, b, c]
//Set
Set<String> streamSet = list.stream().collect(Collectors.toSet());
System.out.println(streamSet);//[a, b, c]
//Map
Map<Integer, String> streamMap = list.stream().collect(Collectors.toMap(item -> item.hashCode(), item -> item));
System.out.println(streamMap);//{97=a, 98=b, 99=c}

结果:[a, b, c] 

           [a, b, c] 

           {97=a, 98=b, 99=c}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值