Home > other >  Sort sublist based on the ordering of superlist
Sort sublist based on the ordering of superlist

Time:06-13

Suppose we have the list [3,7,2,8,1,9,4] and the sublist [4,1,7,9].

We want to sort the sublist such that the ordering of its elements becomes the same as the ordering of the same elements in the superlist.

[4,1,7,9] -> [7,1,9,4]

What is an efficient and elegant way of achieving this in Java?

CodePudding user response:

i assume that list and sublist is arrayList

list.forEach(l -> {
    var index = Iterables.indexOf(subList, s -> s == l);
    if (index != -1) {
        subList.add(subList.get(index));
        subList.remove(index);
    }
});

CodePudding user response:

Also assuming that list and subList are of type ArrayList but using the java8 strean api.

var list = List.of(3,7,2,8,1,9,4);
var subList = List.of(4,1,7,9);

var orderedList = subList.stream()
      .sorted(Comparator.comparing(list::indexOf))
      .collect(Collectors.toList());
  • Related