Java使用流Stream对集合List进行过滤去重,对象和基本数据类型-数据去重
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
- 1、创建工具类 、、、、2、如,本方法测试,直接复制到类引用
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
public class CollectionUtilsPan {
public static <T> Predicate<T> distinctByKey(Function<? super T, Object> keyExtractor) {
Map<Object, Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
}
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.jd.open.api.sdk.internal.util.StringUtil;
import com.kingmed.km2c.baidu.vo.organ.NcpOrganWorkTimeVo;
import com.kingmed.km2c.organ.entity.NcpOrganWorkdate;
import com.kingmed.km2c.util.CollectionUtils2C;
import com.kingmed.km2c.util.DateUtils2C;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.PasswordUtil;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
@Data
public class TestPan {
private String id;
private String name;
public static void main(String[] args) throws Exception{
List<TestPan> testPanList = new ArrayList<>();
TestPan testPan1 = new TestPan();
testPan1.setId("1");
testPan1.setName("555");
TestPan testPan2 = new TestPan();
testPan2.setId("2");
testPan2.setName("66");
TestPan testPan3 = new TestPan();
testPan3.setId("3");
testPan3.setName("77");
TestPan testPan4 = new TestPan();
testPan4.setId("2");
testPan4.setName("99");
testPanList.add(testPan1);
testPanList.add(testPan2);
testPanList.add(testPan3);
testPanList.add(testPan4);
long count = testPanList.stream().filter(obj -> obj.getId().equals("1")).count();
int size = testPanList.size();
List<TestPan> collect = testPanList.stream().filter(CollectionUtilsPan .distinctByKey(TestPan::getId)).collect(Collectors.toList());
System.out.println(size+"本身集合大小");
System.out.println("*-***********************************");
System.out.println(collect.size()+"去重大小");
System.out.println("获取ID等于 1 的个数为:"+count);
}
}