Home > database >  Java sort one list based on another list
Java sort one list based on another list

Time:09-05

I have two different lists: one unsorted list with name and count properties and sorted list.

List<Pair<String, Long>> listA =  for example "A"->4, "B"->3, "C"->1
List<SortedItem> sortedList = [
        SortedItem(name=B, sortIndex=0),
        SortedItem(name=A, sortIndex=1),
        SortedItem(name=C, sortIndex=2),
        SortedItem(name=C, sortIndex=3),
        SortedItem(name=D, sortIndex=4)
    ]

and I would like based on "sortedList" sort the first unsorted list so result should be

List<Pair<String, Long>> res == "B"->3, "A"->4,"C"->1

I did with map, it's not really performant I guess there is much better solution for this ?

List<Pair<String, Long>> sortedResult = sortedList.stream()
    .map(sortItem -> listA.stream().filter(item -> item.getFirst().equals(sortItem.getName())).collect(Collectors.toList()))
    .filter(Predicate.not(List::isEmpty))
    .flatMap(List::stream)
    .collect(Collectors.toList());

CodePudding user response:

  1. First create a map, with sortedItem.name to its first index in the list

    AtomicInteger index = new AtomicInteger();   
    // keep first index with (oldV, newV) -> oldV
    Map<String, Integer> map = values.stream()
         .collect(Collectors.toMap(s -> s.getName(), s -> index.getAndIncrement(), (oldV, newV) -> oldV));
    
  2. Then use it to sort the list

    listA.sort(Comparator.comparingInt(pair -> map.get(pair.getFirst())));
    

List<SortedItem> sortedList = [
    SortedItem(name=B, sortIndex=0),
    SortedItem(name=A, sortIndex=1),
    SortedItem(name=C, sortIndex=2),
    SortedItem(name=C, sortIndex=3),
    SortedItem(name=D, sortIndex=4)
]
// becomes the map
{A=1, B=0, C=2, D=4}
  • Related