Stream流根据多个字段去重
某科学的南条 人气:5Stream流根据多个字段去重
分组
list.stream().collect(Collectors.groupingBy(ClassEntity::getGrade));
java8有一个collectingAndThen可以根据多个字段去重
list.stream() .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getProfessionId() + ";" + o.getGrade()))), ArrayList::new));
通过hashSet去重:
该种去重是bean完全相同的时候算重复数据
List<String> classNameList = new ArrayList(new HashSet(list));
Stream多字段去重,去重求和
stream进行list的循环遍历。
conver的String由去重条件组成,中间用下划线或特殊字符分割
代码如下:
完整demo如下
附带测试结果
class User { private int id; private String name; private Integer record; public User() { } public User(int id,String name, Integer record) { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getRecord() { return record; } public void setRecord(Integer record) { this.record = record; } }
启动主函数
public class Main { public static void main(String[] args) { List<User> users = new ArrayList<>(); User user1 = new User(); user1.setId(1); user1.setName("小明"); user1.setRecord(50); users.add(user1); User user2 = new User(); user2.setId(1); user2.setName("小明"); user2.setRecord(60); users.add(user2); User user3 = new User(); user3.setId(2); user3.setName("小华"); user3.setRecord(70); users.add(user3); User user4 = new User(); user4.setId(2); user4.setName("小华"); user4.setRecord(80); users.add(user4); User user5 = new User(); user5.setId(3); user5.setName("小芳"); user5.setRecord(100); users.add(user5); Map<String, Integer> conver = new HashMap(); users.stream().forEach(x -> { String cKey = x.getId()+"_"+x.getName(); if (!conver.containsKey(cKey)) { conver.put(cKey, x.getRecord()); } else { Integer temp = conver.get(cKey); conver.put(cKey, (null == temp ? 0 : temp) + (null == x.getRecord() ? 0 : x.getRecord())); } }); System.out.println(conver.size()); for(Map.Entry<String, Integer> entry:conver.entrySet()){ System.out.println("key:"+entry.getKey()+","+"value:"+entry.getValue()); } } }
运行结果如下:
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
加载全部内容