1.列表
1.1基础数据准备
public static void main(String[] args) {
List list1 = Arrays.asList(1, 3, 4, 5);
List list2 = Arrays.asList(1, 3, 6, 8);
List list3 = Arrays.asList(2, 5, 7, 9);
}
1.2两个集合取并集
ListmergedList = Stream .concat(list1.stream(), list2.stream()) .collect(Collectors.toList());
1.3两个集合取并集并去重
ListmergedList = Stream .concat(list1.stream(), list2.stream()) .distinct() .collect(Collectors.toList());
1.4存在于集合1但是不存在与集合2中的数据
ListuniqueList1 = list1 .stream() .filter(i -> !list2.contains(i)) .collect(Collectors.toList());
1.5多个集合取并集
ListmergedList = Stream .of(list1, list2, list3) .flatMap(list -> list.stream()) .collect(Collectors.toList());
1.6多个集合求和
Integer sum = Stream
.of(list1, list2, list3)
.flatMap(list -> list.stream())
.reduce(Integer::sum).orElse(0);
2.Map
2.1数据准备
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
private int grade;
private int classID;
private int studentID;
private String name;
private int age;
}
public static void main(String[] args) {
List studentList = new ArrayList<>();
studentList.add(new Student(1, 1, 1, "小明", 6));
studentList.add(new Student(1, 2, 2, "小红", 6));
studentList.add(new Student(1, 2, 3, "小张", 7));
studentList.add(new Student(2, 1, 4, "小王", 7));
studentList.add(new Student(3, 1, 5, "小宋", 8));
}
2.2以学生唯一标识(学号),将list转为map
MapstudentIdMap = studentList .stream() .collect( Collectors.toMap( student -> student.getStudentID(), student -> student, (curr, lastest) -> lastest) );
2.3以年级进行分组
Map> gradeMap = studentList .stream() .collect(Collectors.groupingBy(Student::getGrade));
2.4以年级班级进行分组
Map>> gradeClassMap = studentList .stream() .collect(Collectors.groupingBy(Student::getGrade, Collectors.groupingBy(Student::getClassID)));
2.5获取每个年级年龄最小的同学,如果年龄相同,则取学号最小的同学
MapgradeMinAgeMap = studentList .stream() .collect(Collectors.groupingBy(Student::getGrade, Collectors.collectingAndThen(Collectors.toList(), list -> list .stream() .sorted(Comparator.comparing(Student::getAge).thenComparing(Student::getStudentID)) .findFirst() .orElse(null))));
3.多层Map
3.1数据准备
public static void main(String[] args) {
Map>>> mulitMap = new HashMap<>();
}
3.2多层map的取值(不存在则创建相应的对象,存在则直接获取)
ListtargetList = mulitMap .computeIfAbsent(1, key -> new HashMap<>()) .computeIfAbsent(2, key -> new HashMap<>()) .computeIfAbsent(3, key -> new ArrayList<>());
3.3多层map的取值并设置兜底数据
ListtargetList = Optional.ofNullable(mulitMap) .map(map -> map.get(1)) .map(map -> map.get(2)) .map(map -> map.get(3)) .orElse(new ArrayList<>());



