Order a list based on another list Java

Viewed 165

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

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

I would just use a map with indexes of each name, to simplify the lookup:

Map<String, Integer> indexOfMap = IntStream.range(0, list2.size())
        .mapToObj(i -> Map.entry(list2.get(i).getName(), i))
        .collect(Collectors.toMap(Entry::getKey, Entry::getValue));

Then implement a Comparator that sorts by looking up names in indexOfMap:

Comparator<Employee> comparator = (a, b) -> 
   indexOfMap.containsKey(a.getName()) && indexOfMap.containsKey(b.getName())
        ? indexOfMap.get(a.getName()) - indexOfMap.get(b.getName())
        : (!indexOfMap.containsKey(a.getName()) ? -1 : 1);

//you can make a copy of list if you don't want to change it
//or you can stick to your stream and just use sorted with the comparator
list.sort(comparator);

Note that the order of the first elements in the resulting list is not deterministic (because it's just all elements not present in list2, with no further ordering). All of the values at the end of the list will be in their order dictated by the list2.

You don't need to create new list. see the below code it is simple 2 step process

 list2.stream().forEach((e)->list.removeIf(employee->employee.getName().equalsIgnoreCase(e.getName())));
        
        list.addAll(list2);

list.stream().forEach((employee)->{
            System.out.println(employee.getName());
        });
Related