0

I got the HashMap:

HashMap<String, List<Value>> facetsInCategories = new HashMap<>();

I need to sort the List of Values inside the value of this HashMap. The value in the list has four fields, and I need to sort the list by the "translatedValue" String. That is why I put "getTranslatedValue" in custom comparator. Here is Value object fields:

public String name;
public int count;
private String translatedValue;
private String translation;

And here is what I tried:

for (List<Value> value : facetsInCategories.values()) {
    Collections.sort(value, new Comparator<Value>() {
            @Override
            public int compare(Value o1, Value o2) {
                return o1.getTranslatedValue().compareTo(o2.getTranslatedValue());
            }
    });
}

I've been doing this for couple of hours now, so I thought you may advise somehow on that.

6
  • 4
    What is the result you are getting and what is the result you are expecting? Commented Oct 16, 2014 at 12:11
  • I would expect above code to sort your Value-objects according to the result of String-compareTo of their 'translatedValue'... is this happening already? Commented Oct 16, 2014 at 12:13
  • 1
    Why do you put the list back on the Map? there is no need for that. Sorting should work file. Commented Oct 16, 2014 at 12:13
  • what I am worried about right now is that for (List<Value> value : facetsInCategories.values()) throws an error on the second iteration. This should not happen in my opinion. Commented Oct 16, 2014 at 12:21
  • facetsInCategories.put("test", value); was just for tests, I deleted it from the question right now. Commented Oct 16, 2014 at 12:22

2 Answers 2

1

Code looks fine. Collections.sort will sort the lists in place.

Why do you need this line?

facetsInCategories.put("test", value);

The lists are already added in the hashmap. And they will be sorted where they are.

From null-safety point of view, you are assuming this will never be null:

o1.getTranslatedValue()
Sign up to request clarification or add additional context in comments.

Comments

0

Comment this line and it should do the trick:

facetsInCategories.put("test", value);

1 Comment

facetsInCategories.put("test", value); was just for tests, I deleted it from the question right now. What I am worried about right now is that for (List<Value> value : facetsInCategories.values()) throws an error on the second iteration. This should not happen in my opinion.

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.