0

I am in need of a data structure, like:

Map<String, List<Profile>> profilePool;

What I need is the list to each key should be sorted. I can do it manually while doing profilePool.put() using some compare objecst on some attribute to keep the list ordered against the key. But can we have a compare function attached to the List<> so that whenever a object is inserted into the list, it should place it at a specific index, maintaining the order?

Or do we have any other data structure, easy to use and does the same task?

3
  • When you don't have duplicate elements, a TreeSet might work Commented Jul 11, 2017 at 14:21
  • 2
    Why is there no sorted list in Java? Commented Jul 11, 2017 at 14:21
  • @SilverNak Thanks. But unfortunately I can have duplicate elements. Commented Jul 11, 2017 at 14:23

2 Answers 2

3

Java doesn't provide it out of the box.
If it is worthy, you could create your own wrapper SortedList class that implements List.

At each time you add an element in it, you could identify the insertion position to use with a binary search and push the new value into this position.

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

5 Comments

"Java doesn't provide it out of the box" If this is the case then, I got my answer. I would have to either implement List or find out some other way to do it. Thanks.
@GhostCat You are right. It would not be as much as efficient to sort it even if Collection.sort() should be relatively fast as the List is already sorted.
Well, reality is again complicated. See stackoverflow.com/questions/168891/… for example.
@Impossible, You are welcome. You could also use a TreeSet if the Set interface and constraints suit to your requirement.
plus one for suggesting to implement List using a wrapper instead of extending ArrayList
1

If duplicate elements (based on .equals()) are fully interchangeable, you could use Guava's SortedMultiset. It only stores one instance of each duplicate element, and the iterator will return that same instance multiple times. That technicality aside, it can function the same as a SortedList.

Map<String, SortedMultiset<Profile>> profilePool;

Comments

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.