使⽤Java8的stream计算交集并集差集
⽅法 / 步骤
基本元素的操作
List<Integer> sourceList =new ArrayList<>();
sourceList.add(1);
sourceList.add(2);
sourceList.add(3);
List<Integer> targetList=new ArrayList<>();
targetList.add(3);
targetList.add(4);
targetList.add(5);
/
/求与⽬标List的交集
List<Integer> noChangeIds = sourceList.stream().filter(source -> ains(source)).List());        System.out.println("noChangeIds_"+String());
//求与⽬标List的差集
List<Integer> waitDelIds = sourceList.stream().filter(source ->!ains(source)).List());        System.out.println("waitDelIds"+ String());
//求与原list的差集
List<Integer> waitInsert = targetList.stream().filter(target ->!ains(target)).List());
System.out.println("waitInsert"+ String());
对象元素的操作
/**
* List对象中的交集并集差集
*/
List<Person> personList =new ArrayList<>();
Person person1 =new Person(1L,"⼩明",1,10);
Person person2 =new Person(2L,"⼩红",2,11);
Person person3 =new Person(3L,"⼩兰",2,10);
Person person4 =new Person(3L,"⼩兰",2,10);
personList.add(person4);
personList.add(person3);
personList.add(person2);
personList.add(person1);
personList.forEach(temp-> System.out.String()));
/**
* 去除重复的对象
*/
//⽅法⼀:
List<Person> distinctPersonList =removeReObjectById(personList);
//⽅法⼆:
//        List<Person> distinctPersonList = personList.stream().llectingAndThen(Collectors
//                                    .toCollection(() -> new TreeSet<>(Comparatorparing(Person::getId))), ArrayList::new));
distinctPersonList.forEach(temp-> System.out.println("distinctPersonList_"+String()));
System.out.println("======================================================");
/**
* 出list中的对象,对应的参数出现了⼏次
*/
Map<Long, Long> idRecount = personList.stream().upingBy(person -> Id(), unting()));        idRecount.forEach((k,v)-> System.out.println("PersonID : "+k+"在List中出现了"+v+"次"));
//出List中重复的对象
List<Long> reIds =new ArrayList<>();
idRecount.forEach((k,v)->{if(v >1){ reIds.add(k);}});
List<Person> findReObjectById = personList.stream().filter(tempPerson -> ains(tempPerso
.llectingAndThen(Collectors
.toCollection(()->new TreeSet<>(Comparatorparing(Person::getId))), ArrayList::new));
findReObjectById.forEach(temp-> System.out.println("findReObjectByIdList"+String()));
}
private List<Person>removeReObjectById(List<Person> personList){
Set<Person> peopleTreeSet =new TreeSet<>(Comparatorparing(Person::getId));
peopleTreeSet.addAll(personList);
return new ArrayList<>(peopleTreeSet);
}
统计字符串总字符出现的次数
/
java stream**
* 统计字符串总字符出现的次数
*/
Map<String, Integer> hashMap =new HashMap<>();
String inputStr ="ABBCCCDDDDFFFFF";
List<String> inputStrAsList = Arrays.asList(inputStr.split(""));
inputStrAsList.forEach(var->{
<(var,1,Integer::sum);
});
hashMap.forEach((k,v)->{
System.out.println("key: "+ k +" 出现次数: "+ v);
});
参考资料 & 致谢
【1】
【2】

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。