I have two list list1 and list2 like below
| List 1 | List 2 |
|---|---|
| {"EmpName":"Tony","EmpId":123} | {"EmpName":"David","EmpId":123} |
| {"EmpName":"Mark","EmpId":123} | {"EmpName":"Steve","EmpId":123} |
| {"EmpName":"Steve","EmpId":123} | {"EmpName":"Mark","EmpId":123} |
| {"EmpName":"David","EmpId":123} | |
| {"EmpName":"John","EmpId":123} | |
| {"EmpName":"Jim","EmpId":123} |
Now I wanted to sort list1 based on list2.
Elements in list1 if not on list2 would be on the top, and if the element is present in list2 then it should be in the same order as list2 .
So I'm expecting the result table to be like this.
| Result list |
|---|
| {"EmpName":"Tony","EmpId":123} |
| {"EmpName":"John","EmpId":123} |
| {"EmpName":"Jim","EmpId":123} |
| {"EmpName":"David","EmpId":123} |
| {"EmpName":"Steve","EmpId":123} |
| {"EmpName":"Mark","EmpId":123} |
I have the below code to do this, and it works. I'm really not sure whether this would break during some case or if there is any better way to achieve this:
List<Employee> list = new ArrayList<>();
list.add(new Employee("Tony",123));
list.add(new Employee("Mark",123));
list.add(new Employee("Steve",123));
list.add(new Employee("David",123));
list.add(new Employee("John",123));
list.add(new Employee("Jim",123));
List<Person> list2 = new ArrayList<>();
list2.add(new Employee("David",123));
list2.add(new Employee("Steve",123));
list2.add(new Employee("Mark",123));
List<Person> newList = new ArrayList<>();
list2.forEach(e->{
if(list.stream().filter(doc->e.getName().equalsIgnoreCase(doc.getName())).findAny().isPresent()){
newList.add(e);
list.removeIf(i->i.getName().equalsIgnoreCase(e.getName()));
}
});
list.addAll(newList);
System.out.println(list);
}
Note : Having an equals and hashCode for Employee is required so that list::contains would work.
First find all the elements in list1 that are not in list2.
list3 = list1.stream()
.filter(Predicate.not(list2::contains))
.collect(Collectors.toList());
Then, if
list1. In this case, just simply add all elements of list2 to list1list3.addAll(list2);
list3.addAll(list2.stream().filter(list1::contains).collect(Collectors.toList()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With