java8 StreamAPI(二) 中间操作

一、中间操作列举

过滤 filter
去重 distinct
排序 sorted
截取 limit
跳跃 skip
转换map/flatMap
其他 peek

二、例子演示
2-1 过滤 filter (获取1~5之间的偶数)

  Arrays.asList(1, 2, 3, 4, 5).stream().filter(x->x%2==0).forEach(System.out::println);

2-2 去重 distinct (去除集合中的重复元素)

 Arrays.asList(1.23,4,5,6,7,7,7,7).stream().distinct().forEach(System.out::println);

2-3 排序 sorted (集合中的元素排序并且是倒序)

 Arrays.asList(1,23,4,5,6).stream().sorted((a,b)->b-a).forEach(System.out::println);

2-4 截取 limit (取集合中的第一条数据)

 Arrays.asList(1,2,34,56,1).stream().limit(1).forEach(System.out::println);

2-5 跳跃 skip (跳过集合中的第一条数据)

 Arrays.asList(1,23,34,5).stream().skip(1).forEach(System.out::println);

2-6 转换map、mapToInt (String转Integer)

 Arrays.asList("1","2","3","5").stream().mapToInt(x->Integer.valueOf(x)).forEach(System.out::println);
 Arrays.asList("1","2","3","5").stream().map(x->Integer.valueOf(x)).forEach(System.out::println);

2-7 转换 flatMap (请动手实践体验map与flatMap的区别)

//flatMap与map的区别在于 flatMap是将一个流中的每个值都转成一个个流,然后再将这些流扁平化成为一个流 。
  String[] strs = {"java8", "is", "easy", "to", "use"};
  Arrays.stream(strs).map(s -> s.split("")).distinct().collect(Collectors.toList()).forEach(System.out::println);
  Arrays.stream(strs).map(s -> s.split("")).flatMap(Arrays::stream).distinct().collect(Collectors.toList()).forEach(System.out::println);

2-7 其他 peek (类似于打印日志的功能在进行操作时查看当前值)

 Arrays.asList("1","2","3","5").stream().peek(System.out::println).forEach(System.out::println);

猜你喜欢

转载自blog.csdn.net/qq_41446768/article/details/87921192