Stream特性
- stream不存储数据
- stream不改变源数据
- stream 不可重复使用
踩坑
// 不改变原来员工集合的方式
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() + "-->" + personListNew.get(0).getSalary());
System.out.println("二次改动后:" + personListNew2.get(0).getName() + "-->" + personListNew.get(0).getSalary());
}
}
输出结果:
一次改动前:Tom–>8900
一次改动后:Tom–>18900
二次改动前:Tom–>18900
二次改动后:Tom–>18900
Stream
steam/lambada学习
Java8 全新Stream 机制详解
Stream API详解
Optional类
lambda表达式
// 按工资倒序排序
List<String> newList2 = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed())
.map(Person::getName).collect(Collectors.toList());
// 先按工资再按年龄升序排序
List<String> newList3 = personList.stream()
.sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName)
.collect(Collectors.toList());
List<String> newList4 = personList.stream().sorted((p1, p2) -> {
if (p1.getSalary() == p2.getSalary()) {
return p2.getAge() - p1.getAge();
} else {
return p2.getSalary() - p1.getSalary();
}
}).map(Person::getName).collect(Collectors.toList());
双冒号用法
流处理之toMap()方法
Map中去除重复映射键,一个IllegalStateException执行收集操作时被抛出。 如果映射的密钥可能有重复,请改用toMap(Function, Function, BinaryOperator)
Map<String, CronusMissionFissionEventDTO> eventMap = missionFinishEventList.stream()
.collect(Collectors.toMap(CronusMissionFissionEventDTO::getEventType, o -> o, (k1, k2) -> k2));
O->O跟Function.identity()意识一样
以下产生一个Map映射学生到他们的平均成绩:
Map<Student, Double> studentToGPA students.stream().collect(toMap(Functions.identity(), student -> computeGPA(student)));
以下产生一个Map映射学生的唯一标识符:
Map<String, Student> studentIdToStudent students.stream().collect(toMap(Student::getId, Functions.identity());
如果您有一个Person的流,并且您想要生成一个“电话簿”映射名称来解决,但是可能有两个人具有相同的名称,您可以按照以下方式优雅地处理这些冲突,并产生一个Map映射名称到一个并置的地址列表:
Map<String, String> phoneBook people.stream().collect(toMap(Person::getName, Person::getAddress, (s, a) -> s + ", " + a));
keyMapper - 产生密钥的映射函数
valueMapper - 产生值的映射函数
mergeFunction - 一个合并函数,用于解决与相同键相关联的值之间的冲突,提供给 Map.merge(Object, Object, BiFunction)
mapSupplier - 返回一个新的空的 Map的函数,其中将插入结果
总结
提示:这里对文章进行总结:
例如:以上就是今天要讲的内容,本文仅仅简单介绍了pandas的使用,而pandas提供了大量能使我们快速便捷地处理数据的函数和方法。