'how to find elements elements which are common in 2 list ,present in list 1 and not present in list2
create a model class namely student,add its setters and getters then create 2 listr of students add value in them and then find the elements which are present in list1 but not in list2,elements which are present in list2 but not in list1, elements which are common in both. use hashmap preferbally.
ListS.add(new Student(1, "ravi"));
ListS.add(new Student(2, "habib"));
ListS.add(new Student(3, "enam"));
ListS.add(new Student(4, "sar"));
// List<Student> ListS1 = new ArrayList<Student>();
ListS1.add(new Student(1, "sar"));
ListS1.add(new Student(2, "habib"));
ListS1.add(new Student(3, "par"));
ListS1.add(new Student(4, "sdcs"));
HashMap<Integer,String > map1 = new HashMap<Integer,String >();
HashMap<Student,Integer > commonMap = new HashMap<Student,Integer>();
for (Student stud:ListS) {
map1.put(stud.getId(), stud.getName());
}
for (int i = 0; i <ListS.size() ; i++) {
if(map1.containsKey(ListS.get(i))){
commonMap.put(ListS.get(i),i);
System.out.println(commonMap);
}
}
Solution 1:[1]
I'd rather recommend to use Set instead of Map because you dont need a key-value pair. Since Set cannot contain duplicates it is a perfect match for union. Keep in mind if you work with objects you have to correctly override equals() method. If you need duplicate values use list instead.
List<Integer> list1 = List.of(1, 2, 3);
List<Integer> list2 = List.of(2, 3, 4);
Set<Integer> union = Stream
.concat(list1.stream(), list2.stream())
.collect(Collectors.toSet());
Set<Integer> list1UniqueValues = list1.stream()
.filter(e -> !list2.contains(e))
.collect(Collectors.toSet());
Set<Integer> list2UniqueValues = list2.stream()
.filter(e -> !list1.contains(e))
.collect(Collectors.toSet());
System.out.println(union); // [1, 2, 3, 4]
System.out.println(list1UniqueValues); // [1]
System.out.println(list2UniqueValues); // [4]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
