title:Java的Stream表达式
Java的Stream表达式 一、如何理解Stream
-
Java8新特性
Stream可以理解为管道,管道里的流水就是数据,管道里可以对水进行处理,如过滤,消毒,净化等等 *** 作。最后流出的水才能喝。
所以我理解Stream关注的是对数据的加工计算。对比java集合框架,集合框架关注的是如何存取数据。
-
一个stream *** 作主要有3个部分:源头、中间 *** 作、终止 *** 作。
中间 *** 作可以有0个或多个 但不是立马执行的,只有终止 *** 作被调用后中间 *** 作才会一起执行(惰性执行)
-
有了stream *** 作后 会简化我们的 *** 作,如循环
如循环一个数组,打印,如下 *** 作,而非原来的for循环,是否很简洁
int[] intArray = new int[]{2,4,6,1}; Arrays.stream(intArray).forEach(System.out::println);
-
数组
int[] intArray = new int[]{2,4,6,1}; Arrays.stream(intArray).forEach(System.out::println); Stream.of(intArray).forEach(System.out::println);
-
集合
strList.stream().forEach(System.out::println); Stream.of(strList).forEach(System.out::println);
-
主要有filter map flatmap sorted skip limit distinct
-
筛选与切片 filter、limit、skip、distinct
//filter --帅选出想要的数据 List<String> list = Arrays.asList("bbb", "aaa", "ddd", "aaa", "ccc", "ddd", "eee"); list.stream().filter(e -> "aaa".equals(e)).forEach(e -> System.out.print(e + " ")); outPut : aaa aaa //limit --截断流,使其元素不能超过给定数量 List<String> list = Arrays.asList("bbb", "aaa", "ddd", "aaa", "ccc", "ddd", "eee"); list.stream().filter(e -> "aaa".equals(e)).limit(1).forEach(e -> System.out.print(e + " ")); outPut : aaa //ship --跳过元素,返回一个扔掉了前n个元素的流,若流中元素不足n个,则返回一个空流,与limit(n)互补 List<String> list = Arrays.asList("bbb", "aaa", "ddd", "aaa", "ccc", "ddd", "eee"); list.stream().skip(2).forEach(e -> System.out.print(e + " ")); outPut : ddd aaa ccc ddd eee //distinct --筛选,通过流所生成元素的hashCode()和equals()去除重复元素 List<String> list = Arrays.asList("bbb", "aaa", "ddd", "aaa", "ccc", "ddd", "eee"); list.stream().distinct().forEach(e -> System.out.print(e + " ")); outPut : bbb aaa ddd ccc eee
-
映射 map、flatmap
//map --将元素转换成其他形式或提取信息。接收另一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。 List<String> list = Arrays.asList("bbb", "aaa", "ddd", "aaa", "ccc", "ddd", "eee"); list.stream().map(e -> e.toUpperCase()).forEach(e -> System.out.print(e + " ")); outOut : BBB AAA DDD AAA CCC DDD EEE //flatMap --接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有的流连接成一个流 List<String> list = Arrays.asList("bbb", "aaa", "ddd", "aaa", "ccc", "ddd", "eee"); Stream<Stream<Character>> stream = list.stream().limit(2).map(e -> filterCharacter(e)); ----------------------------------------------------------- System.out.print("map:"); //返回的stream里的每个值都是流 stream.forEach(sm -> { sm.forEach(e -> {System.out.print(e + " ");}); }); //outPut : map:b b b a a a ----------------------------------------------------------- System.out.print("flarMap:"); //返回的流直接连接成一个流 Stream<Character> stream2 = list.stream().limit(2).flatMap(e -> filterCharacter(e)); stream2.forEach(e -> System.out.print(e + " ")); //outPut : flarMap:b b b a a a ----------------------------------------------------------- public static Stream<Character> filterCharacter(String str) { List<Character> list = new ArrayList<>(); for (Character ch : str.toCharArray()) { list.add(ch); } return list.stream(); }
-
排序 sorted
//sorted() –-自然排序 List<Integer> list = Arrays.asList(5, 3, 4, 1, 2); list.stream().sorted().forEach(e -> System.out.print(e + " ")); outPut : 1 2 3 4 5 //sorted(comparator com) –-定制排序 List<Integer> list = Arrays.asList(5, 3, 4, 1, 2); list.stream().sorted((x, y) -> y.compareTo(x)).forEach(e -> System.out.print(e + " ")); outPut : 5 4 3 2 1
-
实战
//分组 classEntities.stream().collect(Collectors.groupingBy(ClassEntity::getGrade)); //stream 去重 多个属性 List<UdPersonBelongDto> udPersonBelongDtoListnew = udPersonBelongDtoList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<(Comparator.comparing(o -> o.getBelongOuUuid() + ";" + o.getExternalId()))), ArrayList::new)); //stream 去重 单个属性 List<UdPersonBelongDto> udPersonBelongDtoListnew = udPersonBelongDtoList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getBelongOuUuid()))), ArrayList::new));
- 主要有reduce、foreach、collect、allMatch、anyMatch、noneMatch、findFirst、findAny、max、min、count
- 示例
import java.util.*;
import java.util.stream.Collectors;
class StreamMode{
private String name;
private int age;
public StreamMode(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "StreamMode{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
public class StreamYf {
public static void main(String[] args) {
List<StreamMode> strList = new ArrayList<>();
StreamMode streamMode1 = new StreamMode("y1",21);
StreamMode streamMode2 = new StreamMode("y3",22);
StreamMode streamMode3 = new StreamMode("y2",23);
StreamMode streamMode4 = new StreamMode("y4",20);
StreamMode streamMode5 = new StreamMode("y5",19);
strList.add(streamMode1);
strList.add(streamMode2);
strList.add(streamMode3);
strList.add(streamMode4);
strList.add(streamMode5);
//map reduce(lamdba需要两个参数)
Optional<Integer> reduce = strList.stream().map(StreamMode::getAge).reduce(Integer::sum);
System.out.println(reduce.get());
//allMatch 全部匹配 (anyMatch noneMatch用法一样)
boolean resultAllMatch = strList.stream().allMatch(x -> x.getAge() > 20);
System.out.println("resultAllMatch="+resultAllMatch);
//findFirst找出排序后的第一个元素(降序即从大到小)
Optional<StreamMode> firstEle = strList.stream().sorted(Comparator.comparingInt(StreamMode::getAge).reversed()).findFirst();
System.out.println("firstEle="+firstEle.get());
//findAny找出任一个元素
Optional<StreamMode> anyEle = strList.stream().findAny();
System.out.println("anyEle="+anyEle.get());
//找出最大的元素 min类似
Optional<Integer> maxAge = strList.stream().map(StreamMode::getAge).max(Integer::max);
System.out.println("maxAge="+maxAge.get());
//统计过滤后元素的个数
long count = strList.stream().filter(x -> x.getAge() > 20).count();
System.out.println("count="+count);
//collect 收集后转为List toSet类似用法
List<Integer> collectList = strList.stream().map(StreamMode::getAge).collect(Collectors.toList());
System.out.println("collectList="+collectList);
//collect 收集后转为Map
Map<String, List<StreamMode>> collectMap = strList.stream().collect(Collectors.groupingBy(StreamMode::getName));
System.out.println("collectMap="+collectMap);
//collect 收集后求平均年龄 sum max 类似
Double collectAvg = strList.stream().collect(Collectors.averagingInt(StreamMode::getAge));
System.out.println("collectAvg="+collectAvg);
//collect 获取SummaryStatistics 可以一次性获取max min sum等
IntSummaryStatistics collectAll = strList.stream().collect(Collectors.summarizingInt(StreamMode::getAge));
System.out.println("collectAvg2="+collectAll.getAverage());
System.out.println("collectCount2="+collectAll.getCount());
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)