1.List根据多个字符串去重
方法一:根据网上描述的重写类的equal。
package lzy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.jws.soap.SOAPBinding.Use;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.CollectionUtils;
import io.netty.util.internal.ConcurrentSet;
@SpringBootTest
public class Test {
@org.junit.Test
public void test(){
List<User2> list = new ArrayList<>();
list.add(new User2(1, "张三", "14"));
list.add(new User2(1, "chen三", "14"));
list.add(new User2(2, "李三", "14"));
list.add(new User2(3, "王三", "14"));
list.add(new User2(3, "王三", "19"));
//方法一:重写equal
List<User2> removeDuplicateInvoice = removeDuplicateInvoice(list);
//方法二:用lambda表达式
List<User2> result = null;
result = list.stream()
.filter((User2 s) -> 1==s.getId()&&"14".equals(s.getAge()))
.collect(Collectors.toList());
//方法三:利用Collectors.toCollection(() 和TreeSet去重
List<User2> distinctList = list.stream()
.collect(Collectors.collectingAndThen(Collectors.toCollection(()
-> new TreeSet<>(Comparator.comparing(u->u.getAge()+u.getId()))), ArrayList::new));
//部分参考:https://blog.csdn.net/u012060033/article/details/103683494
}
/**
* List去重
* @param tList 对象列表
* @param function 实现apply方法,获取去重属性值
* @param <T> 泛型去重对象
* @param <R> 泛型去重属性值
* @return 去重之后的列表
*/
public static <T, R> List<T> distinctByKey(List<T> tList, Function<? super T, R> function) {
List<T> otherList = new ArrayList<>();
Set<R> set = new ConcurrentSet<>();
for (T t : tList) {
R r = function.apply(t);
if (!set.contains(r)) {
set.add(r);
otherList.add(t);
}
}
return otherList;
}
// 去重(重写equals方法)
private static List<User2> removeDuplicateInvoice(List<User2> orderList) {
List<User2> list = new ArrayList<>();
if (!CollectionUtils.isEmpty(orderList)) {
for (User2 user : orderList) {
// list去重复,内部重写equals
if (!list.contains(user)) {
list.add(user);
}
}
}
return list;
}
}
class User2{
private Integer id;
private String name;
private String age;
public User2(Integer id, String name, String age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
public User2()
{
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this == obj) {
return true;
}
User2 drug = (User2) obj;
if (this.getAge().equals(drug.getAge()) && this.getId().equals(drug.getId())){
return true;
}
return false;
}
}