Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order a list based on another list Java

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

    }
like image 616
Jeeppp Avatar asked Jan 26 '26 18:01

Jeeppp


1 Answers

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

  1. There are no elements in list2 which are NOT part of list1. In this case, just simply add all elements of list2 to list1
list3.addAll(list2);
  1. There are elements in list2 which may/may not be in list1. Add elements from list2 which are in list1 to list3.
list3.addAll(list2.stream().filter(list1::contains).collect(Collectors.toList()));
like image 139
Gautham M Avatar answered Jan 29 '26 09:01

Gautham M



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!