java list 去重_Java lambda list,map,转换,过滤,去重操作

1、实体类

package com.lzk.test01.entity;public classPerson {privateLong id;privateString code;publicLong getId() {returnid;

}public voidsetId(Long id) {this.id =id;

}publicString getCode() {returncode;

}public voidsetCode(String code) {this.code =code;

}publicString getName() {returnname;

}public voidsetName(String name) {this.name =name;

}publicString getGender() {returngender;

}public voidsetGender(String gender) {this.gender =gender;

}publicInteger getAge() {returnage;

}public voidsetAge(Integer age) {this.age =age;

}privateString name;privateString gender;privateInteger 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 classTestLaambdaMap {public static voidmain(String[] args) {

List personList = new ArrayList<>();for (int i = 0; i < 10; i++) {

Person person= newPerson();

person.setId((long) i);

person.setName("张三" +i);

person.setSex("男");

person.setAge(18);

personList.add(person);

}

Map collect = personList.stream().collect(Collectors.toMap(person -> person.getId() + person.getName(), person ->person));

System.out.println(collect);

}

}

3、list集合本身以某个属性作为目标去重

List collect = personList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getName))), ArrayList::new));

4、两个list比对,取出交集

List commonList= Person1.stream().filter(item -> item.getName.equals(person2.getName())).collect(Collectors.toList());

5、两个list比对,取出差集

List commonList= Person1.stream().filter(item -> !item.getName.equals(person2.getName())).collect(Collectors.toList());

6、获取list集合中单个属性作为一个集合

List courseIds= users.stream().map(UserEntity::getUserName).collect(Collectors.toList());

7、获取list集合中多个属性组成一个新的list集合(效率比较差)

List collect = personList.stream().map(Person -> new A(Person.getId(), Person.getName())).collect(Collectors.toList());

你可能感兴趣的:(java,list<map>,去重)