How do I sort two arrays in relation to each other?

If you really don’t want to redo your data-structures to combine the infos, you can use a Multimap to do it.

This example utilizes the excellent Google-Guava Library, which you should be using anyway 🙂 https://code.google.com/p/guava-libraries/

String[] names = new String[] {"Monkey1", "Dog2", "Horse3", "Cow4", "Spider5"};
int[] data = new int[] {1,2,3,4,5};

/* guava, throws an IllegalStateException if your array aren't of the same length */
Preconditions.checkState(names.length == data.length, "data and names must be of equal length");

/* put your values in a MultiMap */
Multimap<String, Integer> multiMap = LinkedListMultimap.create();
for (int i=0; i<names.length; i++) {
    mmap.put(names[i], data[i]);
}

/* our output, 'newArrayList()' is just a guava convenience function */
List<String> sortedNames = Lists.newArrayList();
List<Integer> sortedData = Lists.newArrayList();

/* cycle through a sorted copy of the MultiMap's keys... */
for (String name : Ordering.natural().sortedCopy(mmap.keys())) {

    /* ...and add all of the associated values to the lists */
    for (Integer value : mmap.get(name)) {
        sortedNames.add(name);
        sortedData.add(value);
    }
}

Leave a Comment