Home > OS >  Sorting an arrayList based on how another unsorted arrayList would be sorted java
Sorting an arrayList based on how another unsorted arrayList would be sorted java

Time:06-11

I have 3 arrayLists that carry a single entry between them. I can't create a new class to carry that entry. I want to sort all of them based on the values one of the arrayLists. This is closest I've come but .indexOf(item) doesn't give what I want if all the indexes aren't unique. Is there a way I can get the index of item instead of the value of it or is there a different better way to do this?

Collections.sort(scoreListNames, Comparator.comparing(item -> scoreListScores.get(scoreListNames.indexOf(item))));

Collections.sort(scoreListWords, Comparator.comparing(item -> scoreListScores.get(scoreListWords.indexOf(item))));

Collections.sort(scoreListScores);

CodePudding user response:

Java doesn't provide a good way to do this because no serious project would care about your artificial constraint. The whole idea of abstract data types like List is to make the inner workings of operations like sort opaque. Programming is about thinking in harmony with your chosen language, not forcing it to do things in unintended ways.

That said, curiosity is also excellent. So...

You could implement your own sort. When it moves the elements of the list containing the keys, it makes the same moves in the other lists.

Another way is by sorting an index on the list of keys and using it to create new lists that are sorted. Code below sorts on string array s and rearranges the integers in i to match:

// Build some test data.
List<Integer> i = Stream.of(19, 2, 42, 17).collect(Collectors.toList());
List<String> s = Stream.of("cat", "ant", "bat", "Dog").collect(Collectors.toList());

// Create an index.
List<Integer> index = IntStream.range(0, i.size()).boxed().collect(Collectors.toList());

// Sort the indices using references into the string list.
index.sort((a, b) -> s.get(a).compareTo(s.get(b)));

// Apply the index to make new, sorted arrays.
List<String> sSorted = index.stream().map(ix -> s.get(ix)).collect(Collectors.toList());
List<Integer> iSorted = index.stream().map(ix -> i.get(ix)).collect(Collectors.toList());
  • Related