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);
}