1.根据list某字段分组
/**
*List里面的对象元素,以某个属性来分组,例如,以name分组,将name相同的放在一起:
**/
Map<String, List<user>> listMap = list.stream().collect(Collectors.groupingBy(user::getName));
2.//根据list对象中的某个字段进行去重处理
List<IdsHandoverLog> idsHandoverLogs =idsHandoverLogs.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(IdsHandoverLog::getHandoverLogId))), ArrayList::new));
3.list转map
/**
* List -> Map
* 需要注意的是:
* toMap 如果集合对象有重复的key,会报错Duplicate key ....
* apple1,apple12的id都为1。
* 可以用 (k1,k2)->k1 来设置,如果有重复的key,则保留key1,舍弃key2
*/
Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));
/**
* List -> Map 多属性组合成key
**/
Map<String, IdsAlarmLogPipeNetwork> map= appleList.stream().collect(Collectors.toMap(k -> k.getId() + k.getName(), Function.identity()));
4.list过滤Filter,根据对象中属性值过滤
//过滤出符合条件的数据
List<Apple> filterList = appleList.stream().filter(a -> a.getName().equals("张三")).collect(Collectors.toList());
5.提取对象集合中的某个属性组成新的集合
List<String> HandoverLogIdList = idsHandoverLogs.stream().map(o -> o.getHandoverLogId()).collect(Collectors.toList());
5.判断List对象中是否有符合条件的
/**
* anyMatch(Predicate p) 传入一个断言型函数,对流中所有的元素进行判断,
* 只要有一个满足条件就返回true,都不满足返回false。
*/
public static void main(String [] args) {
Student stu1 = new Student(01, 19, "张三");
Student stu2 = new Student(02, 23, "李四");
Student stu3 = new Student(01, 28, "王五");
List<Student> list = new ArrayList<>();
list.add(stu1);
list.add(stu2);
list.add(stu3);
// 判断学生年龄是否包含28岁的
boolean anyMatchFlag = list.stream().anyMatch(student -> student.getAge().equals(28));
System.out.println(anyMatchFlag);
}