Reputation: 1925
I need to sort List by Map, using key of Map. Firstly look at code, afterwards listen to me. I would like to sort List by Key, and after by Value. The result after all should be the following(return only value in List):
/* The result(List):
str3
str1
str2
str4 */
--
List<String> list = ArrayList<>();
list.add("str1");
list.add("str1");
list.add("str3");
list.add("str4"); .......
Map<String, Integer> counts = new HashMap<>();
for (String item:list) {
Integer count = counts.get(item);
if (count == null) {
count = 1;
} else {
count = count + 1;
}
counts.put(item, count);
}
for (Entry<String, Integer> entry : counts.entrySet()) {
System.out.println(entry.getValue() + " " + entry.getKey());
}
--
/* The result:
2 str1
3 str2
1 str3
3 str4 */
Upvotes: 0
Views: 120
Reputation: 13177
Make a custom comparator:
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String left, String right) {
return Integer.compare(counts.get(left), counts.get(right));
}
});
Note that you need to make counts
final
for this to work.
Running this on your example:
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("str1");
list.add("str2");
list.add("str3");
list.add("str4");
final Map<String, Integer> counts = new HashMap<>();
counts.put("str1", 2);
counts.put("str2", 3);
counts.put("str3", 1);
counts.put("str4", 3);
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String left, String right) {
return Integer.compare(counts.get(left), counts.get(right));
}
});
System.out.println(list);
}
}
Yields:
[str3, str1, str2, str4]
Upvotes: 1