
今天遇到一个业务场景,有一个数据容器是 Map,现在需要根据 Map的 value来排序,这个实现简单记录下,也算水一篇博文了。
kotlin 因为将Map定义为了同Python一样的元组(Tuple/Pair)所以代码实现起来要简单很多。
@Test
fun test1() {
//初始化
val map = mapOf("ba" to 1, "bccc" to 4, "bxc" to 3, "aeel" to 3)
//转换的核心代码
val toMap = map.toList().sortedBy { it.second }.toMap()
//输出代码
println(toMap.toJson())
}
map.toList()是kotlin的扩展方法,将 map转为PairPair的Value就是第二参数second进行排序List<Pair>重新转换为 Map同 Python 的做法很相像
java 的作用相对Kotlin就复杂一些了。
@Test
public void test2() {
//初始化
HashMap<String, String> hashMap = new HashMap();
hashMap.put("a", "1");
hashMap.put("ab", "21");
hashMap.put("c", "5");
//转换的核心代码
LinkedHashMap<String, String> collect = hashMap.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getValue))
//.sorted(Map.Entry.comparingByValue())
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue,
(ov, nv) -> ov, LinkedHashMap::new));
//输出代码
System.out.println(JsonUtil.toJsonStr(collect));
}
StreamSet<Entry>Stream流Comparator.comparing(Map.Entry::getValue)toMap转换为 Map其中
Comparator.comparing(Map.Entry::getValue)可以改为更加简单的Map.Entry.comparingByValue(),这是 JDK中专门为此提供的方法。
如果有机会,我还是建议大家学学kotlin和python,应该会让大家受益匪浅的!