简体   繁体   中英

Java sort HashMap values which are List<Value>

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.

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()

评论此行,它应该可以解决问题:

facetsInCategories.put("test", value);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM