Java lambda list,map,转换,过滤,去重操作
1、实体类
package com.lzk.test01.entity; public class Person { private Long id; private String code; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } private String name; private String gender; private Integer age; }
2、Java lambda list转换map,以多个属性作为key值
package com.lzk.test01.test; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class TestLaambdaMap { public static void main(String[] args) { List<Person> personList = new ArrayList<>(); for (int i = 0; i < 10; i++) { Person person = new Person(); person.setId((long) i); person.setName("张三" + i); person.setSex("男"); person.setAge(18); personList.add(person); } Map<String, Person> collect = personList.stream().collect(Collectors.toMap(person -> person.getId() + person.getName(), person -> person)); System.out.println(collect); } }
3、list集合本身以某个属性作为目标去重
List<Person> collect = personList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new));
去重后集合不乱序
List<MetadataExceluploadDTO> deallist = resultremplist.stream() .collect(Collectors.collectingAndThen( Collectors.toMap( // 使用组合键去重:
serviceName + instanceName + tableName + colName item -> item.getServiceName() + item.getInstanceName() + item.getTableName() + item.getColName(), Function.identity(), // 保留原对象
(existing, replacement) -> existing, // 遇到重复键时保留第一个
LinkedHashMap::new // 保持顺序
),
map -> new ArrayList<>(map.values()) // 将 Map 转换回 List
));
4、两个list比对,取出交集
List<PersonCommon> commonList= Person1.stream().filter(item -> item.getName.equals(person2.getName())).collect(Collectors.toList());
5、两个list比对,取出差集
List<PersonCommon> commonList= Person1.stream().filter(item -> !item.getName.equals(person2.getName())).collect(Collectors.toList());
6、获取list集合中单个属性作为一个集合
List<String> courseIds= users.stream().map(UserEntity::getUserName).collect(Collectors.toList());
7、获取list集合中多个属性组成一个新的list集合(效率比较差)
List<A> collect = personList.stream().map(Person -> new A(Person.getId(), Person.getName())).collect(Collectors.toList());
使用lombok的@Builder注解
List<AppNameAddrDTO> collect = applicationList.stream().map(item -> AppNameAddrDTO.builder()
.appName(item.getAppName())
.appAddress(item.getAppAddress()).build()).collect(Collectors.toList());
8、指定字段分组
9、匹配获取最大值
10、分组求和