Java 函数式编程 stream流(一)
1. Stream和parallelStream
stream是顺序流,由主线程按顺序对流执行操作,而parallelStream是并行流,内部以多线程并行执行的方式对流进行操作,但前提是流中的数据处理没有顺序要求。如果流中的数据量足够大,并行流可以加快处速度。除了直接创建并行流,还可以通过parallel()把顺序流转换成并行流:
Optional<Integer> findFirst = list.stream().parallel().filter(x->x>6).findFirst();
使用Stream的静态方法生成流:of()、iterate()、generate()
Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5, 6);
Stream<Integer> stream3 = Stream.iterate(0, (x) -> x + 3).limit(4);
stream3.forEach(System.out::println);
Stream<Double> stream4 = Stream.generate(Math::random).limit(3);
stream4.forEach(System.out::println);
2. Stream使用
map:接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person("张三", 1000, 20, "男", "北京"));
personList.add(new Person("李四", 2000, 21, "男", "南京"));
personList.add(new Person("王五", 3000, 20, "女", "合肥"));
personList.add(new Person("赵六", 4000, 22, "男", "四川"));
personList.add(new Person("孙七", 5000, 25, "女", "上海"));
List<Person> personListNew = personList.stream().map(person -> {
Person personNew = new Person(person.getName(), 0, 0, null, null);
personNew.setSalary(person.getSalary() + 10000);
return personNew;
}).collect(Collectors.toList());
System.out.println("一次改动前:" + personList.get(0).getName() + ">>>" + personList.get(0).getSalary());
System.out.println("一次改动后:" + personListNew.get(0).getName() + ">>>" + personListNew.get(0).getSalary());
List<Person> personListNew2 = personList.stream().map(person -> {
person.setSalary(person.getSalary() + 10000);
return person;
}).collect(Collectors.toList());
System.out.println("二次改动前:" + personList.get(0).getName() + ">>>" + personList.get(0).getSalary());
System.out.println("二次改动后:" + personListNew2.get(0).getName() + ">>>" + personListNew2.get(0).getSalary());
}
结果:方式一:不改变原来员工集合;方式二:改变原来员工集合的方式
// 将两个字符数组合并成一个新的字符数组
List<String> list = Arrays.asList("Hello", "World");
Stream<String> stringStream = list.stream().map(s -> s.split("")).flatMap(Arrays::stream);
stringStream.forEach(System.out::print);
// 给定两个数字列表 获取所有的数对
List<Integer> numbers1 = Arrays.asList(1, 2, 3);
List<Integer> numbers2 = Arrays.asList(3, 4);
List<int[]> collect = numbers1.stream().flatMap(x -> numbers2.stream().map(y -> new int[]{x, y})).collect(Collectors.toList());
collect.forEach(c-> System.out.println(Arrays.toString(c)));
归集(toMap)
List<Person> personList3 = new ArrayList<>();
personList3.add(new Person("张三", 1000, 20, "男", "北京"));
personList3.add(new Person("李四", 2000, 21, "男", "南京"));
personList3.add(new Person("王五", 3000, 20, "女", "合肥"));
personList3.add(new Person("赵六", 4000, 22, "男", "四川"));
personList3.add(new Person("孙七", 5000, 25, "女", "上海"));
Map<String, Integer> map = personList3.stream().filter(person -> person.getSalary() > 3000).collect(Collectors.toMap(Person::getName, Person::getSalary));
System.out.println("工资大于3000元的员工:" + map);
结果:工资大于3000元的员工:{孙七=5000, 赵六=4000}
统计(count/averaging)
Collectors提供了一系列用于数据统计的静态方法
计数:count
平均值:averagingInt、averagingLong、averagingDouble
最值:maxBy、minBy
求和:summingInt、summingLong、summingDouble
统计以上所有:summarizingInt、summarizingLong、summarizingDouble
List<Person> personList4 = new ArrayList<>();
personList4.add(new Person("张三", 1000, 20, "男", "北京"));
personList4.add(new Person("李四", 2000, 21, "男", "南京"));
personList4.add(new Person("王五", 3000, 20, "女", "合肥"));
personList4.add(new Person("赵六", 4000, 22, "男", "四川"));
personList4.add(new Person("孙七", 5000, 25, "女", "上海"));
// 员工总人数
long count = personList4.stream().count();
// 平均工资
Double salary = personList4.stream().collect(Collectors.averagingDouble(Person::getSalary));
// 最高工资
Optional<Integer> max = personList4.stream().map(Person::getSalary).max(Integer::compare);
// 工资之和
int sum = personList4.stream().mapToInt(Person::getSalary).sum();
//一次性统计所有信息
DoubleSummaryStatistics summaryStatistics = personList4.stream().collect(Collectors.summarizingDouble(Person::getSalary));
System.out.println("员工总人数:" + count);
System.out.println("员工平均工资:" + salary);
System.out.println("员工工资总和:" + max);
System.out.println("员工工资所有统计:" + summaryStatistics);
分组(partitioningBy/groupingBy)
分区:将stream按条件分为两个Map,比如员工按薪资是否高于8000分为两部分。
分组:将集合分为多个Map,比如员工按性别分组。有单级分组和多级分组。
List<Person> personList5 = new ArrayList<>();
personList5.add(new Person("张三", 1000, 20, "男", "北京"));
personList5.add(new Person("李四", 2000, 21, "男", "南京"));
personList5.add(new Person("王五", 3000, 20, "女", "合肥"));
personList5.add(new Person("赵六", 4000, 22, "男", "合肥"));
personList5.add(new Person("孙七", 5000, 25, "女", "上海"));
// 按薪资高于3000分组
Map<Boolean, List<Person>> salaryGroup = personList5.stream().collect(Collectors.partitioningBy(p -> p.getSalary() > 3000));
List<Person> group1 = salaryGroup.get(true);
List<Person> group2 = salaryGroup.get(false);
for (Person person : group1) {
System.out.println("薪资高于3000元组:" + person);
}
for (Person person : group2) {
System.out.println("薪资低于3000元组:" + person);
}
// 按性别分组
Map<String, List<Person>> sexGroup = personList5.stream().collect(Collectors.groupingBy(Person::getSex));
List<Person> group3 = sexGroup.get("男");
List<Person> group4 = sexGroup.get("女");
for (Person person : group3) {
System.out.println("男子组:" + person);
}
for (Person person : group4) {
System.out.println("女子组:" + person);
}
// 将员工先按性别分组,再按地区分组
Map<String, Map<String, List<Person>>> group = personList5.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea)));
Map<String, List<Person>> manGroup = group.get("男");
Map<String, List<Person>> womenGroup = group.get("女");
List<Person> group5 = manGroup.get("合肥");
List<Person> group6 = womenGroup.get("上海");
System.out.println("地区在合肥的男子组:" + group5);
System.out.println("地区在上海的女子组:" + group6);
接合(joining)
joining可以将stream中的元素用特定的连接符(没有的话,则直接连接)连接成一个字符串。
String persons = personList5.stream().map(p -> p.getName() + "-" + p.getSex() + "-" + p.getSalary()).collect(Collectors.joining(","));
System.out.println("所有员工信息:" + persons);
结果:所有员工信息:张三-男-1000,李四-男-2000,王五-女-3000,赵六-男-4000,孙七-女-5000
排序(sorted)
sorted():自然排序,流中元素需实现Comparable接口
sorted(Comparator com):Comparator排序器自定义排序
List<Person> personList6 = new ArrayList<>();
personList6.add(new Person("张三", 16000, 20, "男", "北京"));
personList6.add(new Person("李四", 8500, 21, "男", "南京"));
personList6.add(new Person("王五", 7300, 20, "女", "合肥"));
personList6.add(new Person("赵六", 8000, 22, "男", "合肥"));
personList6.add(new Person("孙七", 15860, 25, "女", "上海"));
// 按工资升序排序(自然排序)
List<String> newList = personList6.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName).collect(Collectors.toList());
// 按工资倒序排序
List<String> newList2 = personList6.stream().sorted(Comparator.comparing(Person::getSalary).reversed()).map(Person::getName).collect(Collectors.toList());
// 先按工资再按年龄升序排序
List<String> newList3 = personList6.stream().sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName).collect(Collectors.toList());
// 先按工资再按年龄自定义排序(降序)
List<String> newList4 = personList6.stream().sorted((p1, p2) -> {
if (p1.getSalary().equals(p2.getSalary())) {
return p2.getAge() - p1.getAge();
} else {
return p2.getSalary() - p1.getSalary();
}
}).map(Person::getName).collect(Collectors.toList());
System.out.println("按工资升序排序:" + newList);
System.out.println("按工资降序排序:" + newList2);
System.out.println("先按工资再按年龄升序排序:" + newList3);
System.out.println("先按工资再按年龄自定义降序排序:" + newList4);
提取/组合
流也可以进行合并、去重、限制、跳过等操作。
String[] arr1 = {"a", "b", "c", "d"};
String[] arr2 = {"d", "e", "f", "g"};
Stream<String> stream1 = Stream.of(arr1);
Stream<String> stream2 = Stream.of(arr2);
// concat:合并两个流 distinct:去重
List<String> collect1 = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList());
List<Integer> collect2 = Stream.iterate(1, x -> x + 2).limit(10).collect(Collectors.toList());
List<Integer> collect3 = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList());
System.out.println("流合并:" + collect1);
System.out.println("limit:" + collect2);
System.out.println("skip:" + collect3);