1

I got the following situation:

I have a list of unsorted keys and a different list of String terms. Both are connected in a way, meaning it looks kinda like this:

1 contents
5 term
2 queue
etc.

This list now contains 1000+ entries and I want to find a fast way to sort these two lists in descending order but of course I need the persistent connection to the strings.

5 term
2 queue
1 contents

I thought about putting the keys and values in a TreeMap, but the thing is, there can be duplicate keys, and I want to preserve them. Any ideas on this?

2 Answers 2

2

Create a class that holds the pair of values.

Make it extend Comparable.

Implement compareTo() so it orders by the number.

Use any of the sorting methods already in the API (Arrays.sort, or a SortedSet).

Have fun.

Sign up to request clarification or add additional context in comments.

4 Comments

Using this approach PogoMips can simply use a List, correct, no need for the TreeMap?
@mikey Yes, no need of a Map. The pairs are kept together because you only deal with the object that encapsulates them.
hmm.. so it works but I'm not really convinced. It takes about 7 seconds to create 1,000 objects and put them in a list. And I'm going to have lists with 10,000+ entries.. are there any other options?
If you know the dimensions a priori, an array should be faster than the usual list. ArrayList has a constructor that accepts an initial capacity too. Other than that, improvements start being more complicated and suited for particular scenarios.
0

Use TreeMap with IntegerComparator implemented like the following:

class IntegerComparator implements Comparator<Integer> {
   public int compare(Integer one, Integer two) {
        return two - one;
   }
}

2 Comments

Not if there are duplicate "keys" (or sorting indexes).
@jarnbjo, duplicate keys only requires that in the map, instead of storing <Integer, String> you store <Integer, List<String>>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.