遍历
-
foreach遍历
list.forEach(str-> System.out.println(str)); -
流遍历
List list = new ArrayList();
list.add(“a”);
list.add(“b”);
list.add(“c”);
list.add(“d”);
List list3 = new ArrayList();
// 过滤字符串为a的元素
list.stream().filter(str -> !“a”.equals(str)).forEach(str -> {
list3.add(str);
});
System.out.println(list3);
排序
- 通过student的id进行排序
List sortedIds = list.stream()
.sorted(Comparator.comparingLong(student::getId))
.collect(Collectors.toList());
分組
List list
-
通过单一属性(年龄)进行分组:
Map<String, List> groupedMap =
list.stream()
.collect(Collectors.groupingBy(Student::getAge));
得到的map集合中: key就是每一个age value就是每一个age对应的list -
根据多个属性(年龄和性别)进行分组
得到的集合是一个年龄下分为两种性别(嵌套调用groupby)
Map<String, Map<String, List>> groupedMap = list.stream()
.collect(Collectors.groupingBy(Student::getAge, Collectors.groupingBy(Student::getSex))); -
根据组合属性(年龄和性别组合)进行分组
private static String fetchGroupKey(Student student) {
return student.getAge() + “_” + student.getSex();
} //组合字段Map<String, List> groupedMap =
list.stream()
.collect(Collectors.groupingBy(d -> fetchGroupKey(d)));
去重
-
对于string列表去重
List stringList;
stringList = stringList.stream().distinct().collect(Collectors.toList()); -
对于实体类的去重
List studentList;
studentList = studentList.stream().distinct().collect(Collectors.toList());
distinct()方法是通过hashcode()和equals()方法来获取不同元素,因此需要去重的类必须实现hashcode()和equals()方法。同理也可以通过重写定制的hashcode()和equals()方法来达到某些特殊需求的去重。
-
根据 List 中 Object 某个属性去重(姓名去重)
List studentList;
studentList = studentList.stream()
.collect(collectingAndThen(toCollection(()
-> new TreeSet<>(Comparator.comparing(Student::getName))), ArrayList::new)); -
根据List 中 Object 多个属性去重(姓名,年龄去重)
ListstudentList;
studentList=studentList.stream()
.collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getName() + “;” + o.getAge()))), ArrayList::new));