1.map()方法:实现将流中的元素映射映射到另一个流中,一般的应用场景可以将当前流的数据类型转换成另一种类型的数据类型(这里提供了两种转化类型的写法)
String[]test= {"1","5","3","4","2","2"};
Stream<String> stringStream = Stream.of(test);
stringStream.map(msg->Integer.parseInt(msg))
// .map(Integer::parseInt)
.forEach(System.out::println);
2.sorted():实现排序功能,如果默认的就变成按照正常的数据进行排序,也可以进行自定义进行排序,代码如下:
stringStream.map(msg->Integer.parseInt(msg))
// .sorted()//默认使用数字的正常排序
.sorted((o1,o2)->o1-o2)//根据比较强指定排序规则
.distinct()//去除了重复的
.forEach(System.out::println);
3.distinct()方法:实现去重,如果是对象的去从,需要重写hashcode和equals方法,不然无法去重
stringStream.map(msg->Integer.parseInt(msg))
// .sorted()//默认使用数字的正常排序
.sorted((o1,o2)->o1-o2)//根据比较强指定排序规则
.distinct()//去除了重复的
.forEach(System.out::println);
Stream.of(new User("张三","123"),
new User("李四","143"),
new User("李四","143"))
.distinct()
.forEach(System.out::println);
主要,这里去重的根据这两个字段来去重,所以重写hashcode和equals方法的时候需要设置这两个字段就可以
4.reduce()方法:实现数据归纳得到一个数字,如实现数组的相加:
Integer reduce = Stream.of(2, 3, 6, 9)
.reduce(0, (x, y) -> {
return x + y;
});
System.out.println(reduce);
获取数组的最大值:
Integer reduce1 = Stream.of(2, 6, 5, 9, 21, 1)
.reduce(0, (x, y) -> {
return x > y ? x : y;
});
System.out.println(reduce1);
一般reduce与map相结合;首先对对象的某个属性进行转换之后进行归集
Integer reduce2 = Stream.of(new User("张三", "123"),
new User("李四", "143"),
new User("李四", "143"))
.map(p -> Integer.parseInt(p.getAddress()))
.reduce(0, (x, y) -> x + y);
System.out.println(reduce2);
5.concat():实现两个流的拼接:
Stream<String> a = Stream.of("a", "g", "7");
Stream<String> y = Stream.of("y", "u", "i");
Stream.concat(a,y).forEach(System.out::println);
待续,后面会继续更新jdk8新特性。。。。。。