java8 list简单操作
public static void main(String[] args) {
List<Student> studentList = new ArrayList<>();
studentList.add(Student.randomStudent());
studentList.add(Student.randomStudent());
studentList.add(Student.randomStudent());
studentList.add(Student.randomStudent());
studentList.add(Student.randomStudent());
studentList.add(Student.randomStudent());
studentList.add(Student.randomStudent());
studentList.add(Student.randomStudent());
studentList.add(Student.randomStudent());
studentList.add(Student.randomStudent());
//打印 Student
System.out.println("打印************student start");
studentList.stream().forEach(s->{
System.out.println(s.toString());
});
System.out.println("打印************student end");
//student -> list
List<String> nameList = studentList.stream().map(Student::getName).collect(Collectors.toList());
System.out.println("name *************** start");
nameList.stream().forEach(name->{
System.out.println(name);
});
System.out.println("name *************** end");
//以性别分割
System.out.println("*******用MAP作性别分割******");
Map<Integer,List<Student>> sexListMap = studentList.stream().collect(Collectors.groupingBy(Student::getSex));
for (Map.Entry<Integer, List<Student>> entry : sexListMap.entrySet()){
System.out.println("*********key:*********"+entry.getKey());
entry.getValue().stream().forEach(v->{
System.out.println(v.toString());
});
}
Student maxAgeStudent = studentList.stream().max((s1,s2)->{
return s1.getAge() - s2.getAge();
}).orElse(null);
System.out.println("MAX 年级最大的Student "+maxAgeStudent);
//排序
List<Student> ageOrderStudentList = studentList.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());
List<Student> ageReverseStudentList = studentList.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());
System.out.println("排序 age order");
ageOrderStudentList.forEach(System.out::println);
System.out.println("排序 age reverse");
ageReverseStudentList.forEach(System.out::println);
System.out.println("排序 通用");
studentList.stream().sorted((t1,t2)->{
return t1.getAge() - t2.getAge();
}).forEach(System.out::println);
//去重
System.out.println("用某个属性去重");
List<Student> scoreUniqueList = studentList.stream().collect(
Collectors.collectingAndThen(Collectors.toCollection(
()->new TreeSet<>(Comparator.comparingLong(Student::getScore))),ArrayList::new)
);
scoreUniqueList.forEach(System.out::println);
}