发布日期:2018-03-26
在Java中通过Value对Map<Key , Value>进行排序+ 查看更多
在Java中通过Value对Map<Key , Value>进行排序
+ 查看更多
发布日期:2018-03-10 14:00
分类:JAVA
浏览次数:116
在Java中通过Value对Map<Key , Value>进行排序
我是一个Java初学者。我经常需要按照 Value 对 Map<Key, Value> 排序。
由于 Value 是不唯一的,所以我会首先把 keySet 转换成 array 。然后在 Arrays.sort 中使用自定义的 Comparator 接口函数,根据与Key 有关的 Value 对该 array 进行排序。
有更简单的方法吗?
回答
import java.util.*; public class MapUtil { public static这是一个相关联的JUnit4 测试:> Map sortByValue( Map map ) { List > list = new LinkedList >( map.entrySet() ); Collections.sort( list, new Comparator >() { public int compare( Map.Entry o1, Map.Entry o2 ) { return (o1.getValue()).compareTo( o2.getValue() ); } } ); Map result = new LinkedHashMap (); for (Map.Entry entry : list) { result.put( entry.getKey(), entry.getValue() ); } return result; } }
import java.util.*; import org.junit.*; public class MapUtilTest { @Test public void testSortByValue() { Random random = new Random(System.currentTimeMillis()); MapJava 7 版本:testMap = new HashMap (1000); for(int i = 0 ; i < 1000 ; ++i) { testMap.put( "SomeString" + random.nextInt(), random.nextInt()); } testMap = MapUtil.sortByValue( testMap ); Assert.assertEquals( 1000, testMap.size() ); Integer previous = null; for(Map.Entry entry : testMap.entrySet()) { Assert.assertNotNull( entry.getValue() ); if (previous != null) { Assert.assertTrue( entry.getValue() >= previous ); } previous = entry.getValue(); } } }
public staticJava 8 版本:> Map sortByValue( Map map ) { List > list = new LinkedList<>( map.entrySet() ); Collections.sort( list, new Comparator >() { @Override public int compare( Map.Entry o1, Map.Entry o2 ) { return ( o1.getValue() ).compareTo( o2.getValue() ); } } ); Map result = new LinkedHashMap<>(); for (Map.Entry entry : list) { result.put( entry.getKey(), entry.getValue() ); } return result; }
这将按 Value 升序排列。如果需要降序,只要取消对Collections.reverseOrder() 调用的注释。
public static> Map sortByValue(Map map) { return map.entrySet() .stream() .sorted(Map.Entry.comparingByValue(/*Collections.reverseOrder()*/)) .collect(Collectors.toMap( Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new )); }