Java8 Stream 的使用

Stream概述

Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。也可以使用 Stream API 来并行执行操作。简而言之,Stream API 提供了一种高效且易于使用的处理数据的方式。

需要注意的几点:

  • 不是数据结构,不会保存数据。
  • 不会修改原来的数据源,它会将操作后的数据保存到另外一个对象中。(peek除外)
  • 惰性求值,流在中间处理过程中,只是对操作进行了记录,并不会立即执行,需要等到执行终止操作的时候才会进行实际的计算。

操作分类

中间操作
无状态

指元素的处理不受之前元素的影响;

unordered() filter() map() mapToInt() mapToLong() mapToDouble() flatMap() flatMapToInt() flatMapToLong() flatMapToDouble peek()

有状态

指该操作只有拿到所有元素之后才能继续下去。 例如 排序 去重

distinct() sorted() limit() skip()

结束操作
非短路操作

指必须处理所有元素才能得到最终结果; 例如取 最大最小

forEach() forEachOrdered() toArray() reduce() collect() max() min() count()

短路操作

指遇到某些符合条件的元素就可以得到最终结果,如 A || B,只要A为true,则无需判断B的结果。

anyMatch() allMatch() noneMatch() findFirst() findAny()

流的常用方法

流的创建

// List
List<String> list = new ArrayList<>();
Stream<String> stream = list.stream();// 顺序流
Stream<String> parallelStream = list.parallelStream();// 并行流 多线程
// Array
String[] arr = new String{"x","z","y"};
Stream<String> stream = Arrays.stream(arr);
// 流
BufferedReader reader = new BufferedReader(new FileReader("F:\\test_stream.txt"));
Stream<String> lineStream = reader.lines();
lineStream.forEach(System.out::println);
// 字符串分隔成流
Pattern pattern = Pattern.compile(",");
Stream<String> stringStream = pattern.splitAsStream("a,b,c,d");

流的中间操作

筛选与切片
Stream<Integer> stream = Stream.of(6, 4, 6, 7, 3, 9, 8, 10, 12, 14, 14);
Stream<Integer> ss = stream.filter(s->s>5)	//6 6 7 9 8 10 12 14 14
	.distinct()	// 6 7 9 8 10 12 14
	.skip(2)	// 9 8 10 12 14
	.limit(2);  // 9 8
ss.forEach(System.out::println);
映射(对每项做处理)
// map 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
List<String> list = Arrays.asList("a,b,c", "1,2,3");
//将每个元素转成一个新的且不带逗号的元素
Stream<String> s1 = list.stream().map(s -> s.replaceAll(",", ""));
s1.forEach(System.out::println); // abc  123
 
// flatMap 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流
Stream<String> s3 = list.stream().flatMap(s -> {
    //将每个元素转换成一个stream
    String[] split = s.split(",");
    Stream<String> s2 = Arrays.stream(split);
    return s2;
});
s3.forEach(System.out::println); // a b c 1 2 3
排序
list.stream().sorted(
	(o1,o2) -> {
        return o1.getAge() - o2.getAge();	// o1 o2 实体类 自建 这里只是举个例子
    }
).forEach(System.out::println);
消费
// peek:如同于map,能得到流中的每一个元素。但map接收的是一个Function表达式,有返回值;而peek接收的是Consumer表达式,没有返回值。
Student s1 = new Student("aa", 10);
Student s2 = new Student("bb", 20);
List<Student> studentList = Arrays.asList(s1, s2);
studentList.stream()
        .peek(o -> o.setAge(100))
        .forEach(System.out::println);    
//结果:
Student{name='aa', age=100}
Student{name='bb', age=100}  

流的终止操作

匹配、聚合操作(最大、最小、find…)
allMatch:接收一个 Predicate 函数,当流中每个元素都符合该断言时才返回true,否则返回false 
noneMatch:接收一个 Predicate 函数,当流中每个元素都不符合该断言时才返回true,否则返回false 
anyMatch:接收一个 Predicate 函数,只要流中有一个元素满足该断言则返回true,否则返回false
findFirst:返回流中第一个元素
findAny:返回流中的任意元素
count:返回流中元素的总个数
max:返回流中元素最大值
min:返回流中元素最小值

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);	// 把数组转为list
 
boolean allMatch = list.stream().allMatch(e -> e > 10); //false
boolean noneMatch = list.stream().noneMatch(e -> e > 10); //true
boolean anyMatch = list.stream().anyMatch(e -> e > 4);  //true
 
Integer findFirst = list.stream().findFirst().get(); //1
Integer findAny = list.stream().findAny().get(); //1
 
long count = list.stream().count(); //5
Integer max = list.stream().max(Integer::compareTo).get(); //5
Integer min = list.stream().min(Integer::compareTo).get(); //1
规约操作
// reduce 像是递归
//第一次执行时,accumulator函数的第一个参数为流中的第一个元素,第二个参数为流中元素的第二个元素;第二次执行时,第一个参数为第一次函数执行的结果,第二个参数为流中的第三个元素;依次类推
List<Integer> list=Arrays.asList(1,2,3,4,5);
Integer res = list.stream().reduce((x1,x2)-> x1+x2).get();	//15 注意有get()
Integer res2 = list.stream().reduce(10,(x1,x2)->x1+x2);		//25

Integer v2 = list.stream().reduce(0,
	(x1, x2) -> {
		System.out.println("stream accumulator: x1:" + x1 + "  x2:" + x2);
		 return x1 - x2;
	},
	(x1, x2) -> {
		System.out.println("stream combiner: x1:" + x1 + "  x2:" + x2);
		return x1 * x2;
	});
System.out.println(v2);
// 结果:
stream accumulator: x1:0  x2:1
stream accumulator: x1:-1  x2:2
stream accumulator: x1:-3  x2:3
stream accumulator: x1:-6  x2:4
stream accumulator: x1:-10  x2:5
-15
Collector
// list
List<Integer> ageList = list.stream().map(Student::getAge).collect(Collectors.toList());// Student::getAge 调用getAge()方法
// set
Set<Integer> ageSet = list.stream().map(Student::getAge).collect(Collectors.toSet());
// map key不用相同
Map<String, Integer> studentMap = list.stream().collect(Collectors.toMap(Student::getName, Student::getAge));
// 字符串分隔符连接
String joinName = list.stream().map(Student::getName).collect(Collectors.joining(",", "(", ")"));	// ("xzy","zqy","jay")

// 聚合操作
// 对象总数
int count = list.stream().collect(Collectors.counting());
// 最大年龄
int max = list.stream().map(Stu::getAge).collect(Collectors.maxBy(Integer::compare)).get();
// 总和
Integer sumAge = list.stream().collect(Collectors.summingInt(Student::getAge));
// 平均年龄
Double aveAge = list.stream().collect(Collectors.averagingDouble(Stu::getAge)); 
// 分组
Map<Integer,List<Stu>> ageMap = list.stream().collect(Collectors.groupingBy(Stu::getAge));
// 分区
Map<Boolean, List<Student>> partMap = list.stream().collect(Collectors.partitioningBy(v -> v.getAge() > 10));
// 规约
Integer allAge = list.stream().map(Stu::getAge).collect(Collectors.reducing(Integer::sum)).get();

实际运用

案例一、对每一项进行过滤 并处理
List<FunTreeVO> treeList = list.stream()
    .filter(group -> !group.getFuncId().equals(group.getPFuncId()))	// 过滤没有父子关系的节点
    .map(group -> {	// 映射
        switch(group.getFuncType()){
            case "0":
                group.setFuncType("页面权限");
                break;
            case "1":
                group.setFuncType("操作权限");
                break;
            case "2":
                group.setFuncType("数据权限");
                break;
            default:
                break;
        }
        FunTreeVO node = FuncTreeUtil.setNode(group);	
        node.setIsLeaf(false);
        return node;
    }).collect(Collectors.toList());	// 建树
案例二、从对象list中抽取某一字段的list;两个list的去重并合并
// 从数据库中获取 对象列表
List<VO> list= baseMapper.getData(xx,xx);
// 抽取出来id相关的list
List<String> idList = list.stream().map(VO::getId).collect(Collectors.toList());
...
// 获取一个新的list
List<String> newList = baseMapper.getData2(idList);
// 去重并合并
List<String> resList = Stream.of(idList, newList)
	.flatMap(Collection::stream)
	.distinct()
	.collect(Collectors.toList());

案例四、并集 差集 交集
// 交集
List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(toList());
// 差集 list1 - list2
List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(toList());
// 并集
List<String> listAll = list1.parallelStream().collect(Collectors.toList());
List<String> listAll2 = list2.parallelStream().collect(Collectors.toList());
listAll.addAll(listAll2);
案例五、两个Map处理key冲突
HashMap<String,Integer> map = ...;//获取map
HashMap<String,Integer> map2 = ...;//获取map

// 循环map 获取 key和value
map.forEach((k,v)->{
	/*
	 * k:map的key
	 * v:map的value
	 * (v1,v2):map的value和map2的value
	 */
	map2.merge(k,v,(v1,v2)->{
		// key冲突的处理方法
		return v1+v2;
	});
});
注意:结果保存在map2中!!!
以上方法可以更进一步改写

map.forEach((k,v)->{
    map2.merge(k,v, Integer::sum);
});
案例六、排序并取前十
List<BO> list = ...; //获取BO list

list.stream().sorted(new Comparator<BO>() {
    @Override
    public int compare(BO o1, BO o2) {
        return o2.getNum()-o1.getNum();
    }
}).limit(10).collection(Collectors.toList());

list.stream().limit(10).sorted((o1,o2)->o2.getNum()-o1.getNum()).collection(Collectors.toList());

list = list.stream().sorted((o1, o2) ->{
	o2.getNum() - o1.getNum()
}).limit(10).collection(Collectors.toList());
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值