Sort List using Map, sort it by count
I would like to sort List(list) by Value(count), and after by Key(item).
Asu is ArrayList of String;
System.out.println(asu);
[3100, 3100, 3100, 1029, 1029, 1029, 1029, 1029, 1029, 1029, 100, 100,
100, 100, 100, 2005, 2005, 2005, 2005, 2005, 2005, 2005, 400, 400, 400,
400, 202, 202, 10]
List<String> list = ArrayList<>();
Map<String, Integer> counts = new HashMap<>();
// Fill list with values....
for (String item:list) {
Integer count = counts.get(item);
if (count == null) {
// This is the first time we have seen item, so the count should
be one.
count = 1;
} else {
// Increment the count by one.
count = count + 1;
}
counts.put(item, count);
}
Collections.sort(asu, new Comparator<String>() {
@Override
public int compare(String left, String right) {
return Integer.compare(counts.get(left),
counts.get(right));
}
});
System.out.println(asu);
[10, 202, 202, 3100, 3100, 3100, 400, 400, 400, 400, 100, 100, 100, 100,
100, 1029, 1029, 1029, 1029, 1029, 1029, 1029, 2005, 2005, 2005, 2005,
2005, 2005, 2005,]
The result after all should be the following(return only value in List):
System.out.println(asu);
[10, 202, 202, 3100, 3100, 3100, 400, 400, 400, 400, 100, 100, 100,
100, 100, 2005, 2005, 2005, 2005, 2005, 2005, 2005, 1029, 1029, 1029,
1029, 1029, 1029, 1029]
No comments:
Post a Comment