Java 8 stream的记录
Java 8 stream
Stream 是 Java8 中处理集合的关键抽象概念,它可以指定你希望对集合进行的操作,可以执行非常复杂的查找、过滤和映射数据等操作。使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。也可以使用 Stream API 来并行执行操作。简而言之,Stream API 提供了一种高效且易于使用的处理数据的方式。
1、什么是流
流是从支持数据处理操作的源生成的元素序列,源可以是数组、文件、集合、函数。流不是集合元素,它不是数据结构并不保存数据,它的主要目的在于计算。
如果对以上函数接口不太理解的话,可参考另外一篇文章:Java 8 函数式接口
链接: Java 8 函数式接口
2、如何生成流
生成流的方式主要有五种
1、通过集合生成,应用中最常用的一种
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5, 6);
Stream<Integer> stream = integerList.stream();
2、通过数组生成
int[] intArr = {1, 2, 3, 4, 5, 6};
IntStream stream = Arrays.stream(intArr);
通过Arrays.stream方法生成流,并且该方法生成的流是数值流【即IntStream】而不是 Stream。补充一点使用数值流可以避免计算过程中拆箱装箱,提高性能。
Stream API提供了mapToInt、mapToDouble、mapToLong三种方式将对象流【即Stream 】转换成对应的数值流,同时提供了boxed方法将数值流转换为对象流.
3、通过值生成
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
通过Stream的of方法生成流,通过Stream的empty方法可以生成一个空流.
4、通过文件生成
Stream<String> lines = Files.lines(Paths.get("data.txt"), Charset.defaultCharset());
通过Files.line方法得到一个流,并且得到的每个流是给定文件中的一行
5、通过函数生成
1.iterator
Stream<Integer> stream = Stream.iterate(0, n -> n + 2).limit(5);
iterate方法接受两个参数,第一个为初始化值,第二个为进行的函数操作,因为iterator生成的流为无限流,通过limit方法对流进行了截断,只生成5个偶数。
2.generator
Stream<Double> stream = Stream.generate(Math::random).limit(5);
generate方法接受一个参数,方法参数类型为Supplier ,由它为流提供值。generate生成的流也是无限流,因此通过limit对流进行了截断。
3、流的操作类型
操作分类
stream操作分类 | ||
---|---|---|
中间操作 | 无状态 (stateless) | unordered() fillter() map() mapToInt() peek() mapToDouble() flatMap() ... |
有状态 (staeful) | distinct() sorted() limit() skip() ... | |
结束操作 | 非短路操作 (non-short-circuit operation) | forEach() forEachOrderd() toArray() reduce() collect() max() min() count() ... |
短路操作 (short circuit operation) | anyMatch() allMatch() noneMatch() findFirst() findAny() |
4、常规操作案例
public class StreamDemo {
static List<People> list = null;
//初始化数据
static {
list = Arrays.asList(
new People("1", "Tom", 88, 90),
new People("2", "Jerry", 77, 89),
new People("3", "Lily", 98, 79),
new People("4", "Lucy", 70, 80),
new People("5", "赵二", 88, 90),
new People("6", "HanMeiMei", 87, 79));
}
public void streamtest() {
// filter 过滤器返回还是一个stream流对象
//查询math成绩大于80的学生并遍历输出
list.stream().filter(e -> e.getMath() > 80).forEach(System.out::println);//.forEach(e->System.out.println(e))
//统计数量count
System.out.println(list.stream().count());
//如统计总分大于160的人数
System.out.println(list.stream().filter(e -> e.getEnglish() + e.getMath() > 160).count());
//limit 取前n个值
list.stream().limit(3).forEach(System.out::println);
//skip 跳过前n个
list.stream().skip(2).forEach(System.out::println);
//distinct 去除重复数据
list.stream().distinct().forEach(System.out::println);
//map 映射元素可以对元素进行操作 例如对每个人年龄加1
list.stream().map(e -> {
e.setAge(e.getAge() + 1);
return e;
}).forEach(System.out::println);
//sorted 排序
//升序
list.stream().sorted((a, b) -> {
return a.getEnglish().compareTo(b.getEnglish());
});
List<People> sortenList = list.stream().sorted(Comparator.comparing(People::getAge)).collect(Collectors.toList());
//降序
list.stream().sorted((a, b) -> {
return b.getEnglish().compareTo(a.getEnglish());
});
//自定义排序:先按姓名升序,姓名相同则按年龄升序
list.stream().sorted(
(o1, o2) -> {
if (o1.getName().equals(o2.getName())) {
return o1.getAge() - o2.getAge();
} else {
return o1.getName().compareTo(o2.getName());
}
}
).forEach(System.out::println);
List<People> sortenListDesc = list.stream().sorted(Comparator.comparing(People::getAge).reversed()).collect(Collectors.toList());
//求和字段属性为BigDecimal时:
BigDecimal totalCost = list.stream().map(People::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
//返回第一个元素
Optional<People> first = list.stream().findFirst();
System.out.println(first.get());
//返回任意一个元素
System.out.println(list.stream().findAny().get());
//anyMatch 是否匹配任意一元素 检查是否包含名字为Tom的
System.out.println(list.stream().anyMatch(e -> e.getName().equals("Tom")));
//allMatch 是否匹配所有元素
System.out.println(list.stream().allMatch(e -> e.getName().equals("Tom")));
//noneMatch 是否未匹配所有元素
System.out.println(list.stream().noneMatch(e -> e.getName().equals("Tom")));
//findFirst 返回元素中第一个值
People student = list.stream().findFirst().get();
//findAny 返回元素中任意一个值
People student1 = list.stream().findAny().get();
//max 返回最大值 查询英语成绩最高的学生
People student2 = list.stream().max((l1, l2) -> l2.getEnglish().compareTo(l1.getEnglish())).get();
//min 最小值 将上面l1,l2位置对调
People student3 = list.stream().max((l1, l2) -> l2.getEnglish().compareTo(l1.getEnglish())).get();
/**
* filter:过滤流中的某些元素
* limit(n):获取n个元素
* skip(n):跳过n元素,配合limit(n)可实现分页
* distinct:通过流中元素的 hashCode() 和 equals() 去除重复元素
*/
Stream<Integer> stream = Stream.of(6, 4, 6, 7, 3, 9, 8, 10, 12, 14, 14);
Stream<Integer> newStream = 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
newStream.forEach(System.out::println);
/**
* map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
* flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
* List<String> list = Arrays.asList("a,b,c", "1,2,3");
*/
//将每个元素转成一个新的且不带逗号的元素
Stream<String> s1 = list.stream().map(s -> s.getName().replaceAll(",", ""));
s1.forEach(System.out::println); // abc 123
Stream<String> s3 = list.stream().flatMap(s -> {
//将每个元素转换成一个stream
String[] split = s.getName().split(",");
Stream<String> s2 = Arrays.stream(split);
return s2;
});
s3.forEach(System.out::println); // a b c 1 2 3
}
/**
Reduce常见的用法
*/
public void testReduce() {
Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7, 8});
//求集合元素只和
Integer result = stream.reduce(0, Integer::sum);
System.out.println(result);
stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
//求和
stream.reduce((i, j) -> i + j).ifPresent(System.out::println);
stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
//求最大值
stream.reduce(Integer::max).ifPresent(System.out::println);
stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
//求最小值
stream.reduce(Integer::min).ifPresent(System.out::println);
stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
//做逻辑
stream.reduce((i, j) -> i > j ? j : i).ifPresent(System.out::println);
stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});
//求逻辑求乘机
int result2 = stream.filter(i -> i % 2 == 0).reduce(1, (i, j) -> i * j);
Optional.of(result2).ifPresent(System.out::println);
//拼接字符串
String append = list.stream().map(People::getName).reduce("拼接字符串:", String::concat);
//求平均值
double average = list.stream().mapToInt(People::getAge).average().orElse(0.0);
//求最大值
int min = list.stream().map(People::getAge).reduce(Integer::min).orElse(0);
System.out.println("min : " + min);
//求最小值
int max = list.stream().map(People::getAge).reduce(Integer::max).orElse(0);
System.out.println("max : " + max);
//四种求和的方式
int ageSumThree = list.stream().map(People::getAge).reduce(0, Integer::sum);
System.out.println("ageSumThree: " + ageSumThree);
int ageSumFive = list.stream().map(People::getAge).reduce(Integer::sum).orElse(0);
System.out.println("ageSumFive: " + ageSumFive);
int ageSumOne = list.stream().collect(Collectors.summingInt(People::getAge));
System.out.println("ageSumOne" + ageSumOne);
int ageSumFour = list.stream().mapToInt(People::getAge).sum();
System.out.println("ageSumFour: " + ageSumFour);
}
}
collect 返回集合
/**
* collect:接收一个Collector实例,将流中元素收集成另外一个数据结构。
* Collector<T, A, R> 是一个接口,有以下5个抽象方法:
* Supplier<A> supplier():创建一个结果容器A
* BiConsumer<A, T> accumulator():消费型接口,第一个参数为容器A,第二个参数为流中元素T。
* BinaryOperator<A> combiner():函数接口,该参数的作用跟上一个方法(reduce)中的combiner参数一样,将并行流中各个子进程的运行结果(accumulator函数操作后的容器A)进行合并。
* Function<A, R> finisher():函数式接口,参数为:容器A,返回类型为:collect方法最终想要的结果R。
* Set<Characteristics> characteristics():返回一个不可变的Set集合,用来表明该Collector的特征。有以下三个特征:
* CONCURRENT:表示此收集器支持并发。(官方文档还有其他描述,暂时没去探索,故不作过多翻译)
* UNORDERED:表示该收集操作不会保留流中元素原有的顺序。
* IDENTITY_FINISH:表示finisher参数只是标识而已,可忽略。
*
*/
//装成list
List<Integer> ageList = list.stream().map(People::getAge).collect(Collectors.toList()); // [10, 20, 10]
//转成set
Set<Integer> ageSet = list.stream().map(People::getAge).collect(Collectors.toSet()); // [20, 10]
//转成map,注:key不能相同,否则报错
Map<String, Integer> studentMap = list.stream().collect(Collectors.toMap(People::getName, People::getAge)); // {cc=10, bb=20, aa=10}
//字符串分隔符连接
String joinName = list.stream().map(People::getName).collect(Collectors.joining(",", "(", ")")); // (aa,bb,cc)
//聚合操作
//1.学生总数
Long count = list.stream().collect(Collectors.counting());
//2.最大年龄 (最小的minBy同理)
Integer maxAge = list.stream().map(People::getAge).collect(Collectors.maxBy(Integer::compare)).get();
//3.所有人的年龄
Integer sumAge = list.stream().collect(Collectors.summingInt(People::getAge));
//4.平均年龄
Double averageAge = list.stream().collect(Collectors.averagingDouble(People::getAge)); // 13.333333333333334
// 带上以上所有方法
DoubleSummaryStatistics statistics = list.stream().collect(Collectors.summarizingDouble(People::getAge));
System.out.println("count:" + statistics.getCount() + ",max:" + statistics.getMax() + ",sum:" + statistics.getSum() + ",average:" + statistics.getAverage());
//分组
Map<String, List<People>> collect = list.stream().collect(Collectors.groupingBy(People::getId));
//多重分组,先根据分数分再根据年龄分
Map<Integer, Map<Integer, List<People>>> typeAgeMap = list.stream().collect(Collectors.groupingBy(People::getMath, Collectors.groupingBy(People::getAge)));
//分区
//分成两部分,一部分大于10岁,一部分小于等于10岁
Map<Boolean, List<People>> partMap = list.stream().collect(Collectors.partitioningBy(v -> v.getAge() > 10));
/*List<Map<String, Object>> groupList = list2.stream().collect(Collectors.groupingBy(d -> d.get("region"))).entrySet()
.stream().map(d -> {
Map<String, Object> map = new HashMap<>();
map.put("recruitList", d.getValue());
map.put("region", d.getKey());
return map;
}).collect(Collectors.toList());
*/
reduce的介绍及用法
Optional reduce(BinaryOperator accumulator):第一次执行时,accumulator函数的第一个参数为流中的第一个元素,第二个参数为流中元素的第二个元素;第二次执行时,第一个参数为第一次函数执行的结果,第二个参数为流中的第三个元素;依次类推。
T reduce(T identity, BinaryOperator accumulator):流程跟上面一样,只是第一次执行时,accumulator函数的第一个参数为identity,而第二个参数为流中的第一个元素。
U reduce(U identity,BiFunction<U, ? super T, U> accumulator,BinaryOperator combiner):在串行流(stream)中,该方法跟第二个方法一样,即第三个参数combiner不会起作用。在并行流(parallelStream)中,我们知道流被fork join出多个线程进行执行,此时每个线程的执行流程就跟第二个方法reduce(identity,accumulator)一样,而第三个参数combiner函数,则是将每个线程的执行结果当成一个新的流,然后使用第一个方法reduce(accumulator)流程进行规约。
/** reduce
* Optional<T> reduce(BinaryOperator<T> accumulator):
* 第一次执行时,accumulator函数的第一个参数为流中的第一个元素,第二个参数为流中元素的第二个元素;第二次执行时,第一个参数为第一次函数执行的结果,第二个参数为流中的第三个元素;依次类推。
*
* T reduce(T identity, BinaryOperator<T> accumulator):
* 流程跟上面一样,只是第一次执行时,accumulator函数的第一个参数为identity,而第二个参数为流中的第一个元素。
*
* <U> U reduce(U identity,BiFunction<U, ? super T, U> accumulator,BinaryOperator<U> combiner):
* 在串行流(stream)中,该方法跟第二个方法一样,即第三个参数combiner不会起作用。在并行流(parallelStream)中,我们知道流被fork join出多个线程进行执行,
* 此时每个线程的执行流程就跟第二个方法reduce(identity,accumulator)一样,而第三个参数combiner函数,则是将每个线程的执行结果当成一个新的流,然后使用第一个方法reduce(accumulator)流程进行规约。
*/
//经过测试,当元素个数小于24时,并行时线程数等于元素个数,当大于等于24时,并行时线程数为16
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24);
Integer v = list.stream().reduce((x1, x2) -> x1 + x2).get();
System.out.println(v); // 300
Integer v1 = list.stream().reduce(10, (x1, x2) -> x1 + x2);
System.out.println(v1); //310
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); // -300
Integer v3 = list.parallelStream().reduce(0,
(x1, x2) -> {
System.out.println("parallelStream accumulator: x1:" + x1 + " x2:" + x2);
return x1 - x2;
},
(x1, x2) -> {
System.out.println("parallelStream combiner: x1:" + x1 + " x2:" + x2);
return x1 * x2;
});
System.out.println(v3); //197474048
Steam之两个list间交集、并集、差集
public void listOpt() {
List<String> list1 = new ArrayList();
list1.add("1111");
list1.add("2222");
list1.add("3333");
List<String> list2 = new ArrayList();
list2.add("3333");
list2.add("4444");
list2.add("5555");
// 交集
List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(Collectors.toList());
System.out.println("---得到交集 intersection---");
intersection.parallelStream().forEach(System.out::println);
// 差集 (list1 - list2)
List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(Collectors.toList());
System.out.println("---得到差集 reduce1 (list1 - list2)---");
reduce1.parallelStream().forEach(System.out::println);
// 差集 (list2 - list1)
List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(Collectors.toList());
System.out.println("---得到差集 reduce2 (list2 - list1)---");
reduce2.parallelStream().forEach(System.out::println);
// 并集
List<String> listAll = list1.parallelStream().collect(Collectors.toList());
List<String> listAll2 = list2.parallelStream().collect(Collectors.toList());
listAll.addAll(listAll2);
System.out.println("---得到并集 listAll---");
listAll.parallelStream().forEach(System.out::println);
// 去重并集
List<String> listAllDistinct = listAll.stream().distinct().collect(Collectors.toList());
System.out.println("---得到去重并集 listAllDistinct---");
listAllDistinct.parallelStream().forEach(System.out::println);
System.out.println("---原来的List1---");
list1.parallelStream().forEach(System.out::println);
System.out.println("---原来的List2---");
list2.parallelStream().forEach(System.out::println);
}
list和tree相互转换
/**
* list转树形List
* @param list
* @return
*/
public static List<Zone> list2tree(List<Zone> list) {
List<Zone> result = new ArrayList<>();
Map<String, Zone> map = list.stream().collect(Collectors.toMap(test -> test.getId(), test -> test));
for (Zone test : list) {
Zone p = map.get(test.getParentId());
if (p == null) {
result.add(test);
} else {
if (p.getChildren() == null) {
p.setChildren(new ArrayList<>());
}
p.getChildren().add(test);
}
}
return result;
}
/**
* 树形list转list
* @param list
* @return
*/
public static List<Zone> tree2list(List<Zone> list) {
List<Zone> result = new ArrayList<>();
for (Zone retTreePath : list) {
List<Zone> c = retTreePath.getChildren();
result.add(retTreePath);
if (!CollectionUtils.isEmpty(c)) {
result.addAll(tree2list(c));
retTreePath.setChildren(null);
}
}
return result;
}
stream流式写法把list换为Tree
/**
* 把list换为Tree
*
* @param zoneList
* @return
*/
public static List<Zone> listToTree(List<Zone> zoneList) {
Map<String, List<Zone>> zoneByParentIdMap = zoneList.stream().collect(Collectors.groupingBy(Zone::getParentId));
zoneList.forEach(zone -> zone.setChildren(zoneByParentIdMap.get(zone.getId())));
return zoneList.stream().filter(v -> v.getParentId().equals("0")).collect(Collectors.toList());
}
People.java
public class People {
private String id;
private String name;
private Integer age;
private Integer math;
private Integer english;
private BigDecimal money;
private List<People> children;
public People(String id, String name, Integer age,Integer math) {
this.id = id;
this.name = name;
this.age = age;
this.math=math;
}
}
Zone.java
public class Zone {
private String id;
private String name;
private String parentId;
private List<Zone> children;
public Zone(String id, String name, String parentId) {
this.id = id;
this.name = name;
this.parentId = parentId;
}
public void addChildren(Zone zone) {
if (children == null) {
children = new ArrayList<>();
}
children.add(zone);
}
//get set 方法
}
参考的博客:
Java 8 stream的详细用法