[英]How to sort an ArrayList using a Map key as list object and value as the order?
[英]Sort List by Map, using key and after value
我需要使用Map键按Map排序列表。 首先看代码,然后听我说。 我想按键排序列表,然后按值排序。 毕竟,结果应为以下内容(仅返回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 */
制作自定义比较器:
Collections.sort(list, new Comparator<String>() {
@Override
public int compare(String left, String right) {
return Integer.compare(counts.get(left), counts.get(right));
}
});
请注意,您需要使counts
final
确定才能起作用。
在您的示例上运行此命令:
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);
}
}
产量:
[str3, str1, str2, str4]
当你想阅读键排序Mapentries,你可以使用一个树形图 。 购买也许您可以重新表述这个问题,结果还不清楚。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.