私はこのような比較可能な拡張機能を利用します:
public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map){
List<Map.Entry<K, V>> l = new LinkedList<>(map.entrySet());
Collections.sort(l, new Comparator<Map.Entry<K, V>>()
{
@Override
public int compare(Map.Entry<K, V> one, Map.Entry<K, V> another)
{
return (one.getValue()).compareTo(another.getValue());
}
});
Map<K, V> r = new LinkedHashMap<>();
for (Map.Entry<K, V> item : l)
{
r.put(item.getKey(), item.getValue());
}
return r;
}
私は、このソリューション得たときStreamクラスをしようとしていた。
Map<Long, Date> mapRetrieveMostRecent= new HashMap<>();
Calendar cal = Calendar.getInstance();
mapRetrieveMostRecent.put(1l, cal.getTime());
cal.add(Calendar.DAY_OF_MONTH, -1);
mapRetrieveMostRecent.put(2l, cal.getTime());
cal.add(Calendar.DAY_OF_MONTH, 4);
mapRetrieveMostRecent.put(3l, cal.getTime());
Map<Long, Date> mapRetrieveMostRecentOrdered = sortMap(mapRetrieveMostRecent);
System.out.println("Sorted Map Ascending: " + Arrays.toString(mapRetrieveMostRecentOrdered.entrySet().toArray()));
public static <K, V extends Comparable<? super V>> Map<K,V> sortMap(Map<K,V> map){
return map.entrySet().stream()
.sorted(Map.Entry.comparingByValue())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(e1, e2) -> e2, LinkedHashMap::new));
}
と、対応するテスト:あなたのケースでは
@Test
public void testSortByValue()
{
int testSize = 50;
Random random = new Random(System.currentTimeMillis());
Map<Long, Date> testMap = new HashMap<>(testSize);
for(long i = 0 ; i < testSize ; ++i) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, random.nextInt());
testMap.put(i, cal.getTime());
}
testMap = TenaTest.sortByValue(testMap);//Using compare
//testMap = TenaTest.sortMap(testMap);//Using streams
Assert.assertEquals(testSize, testMap.size());
Date previous = null;
for(Map.Entry<Long, Date> entry : testMap.entrySet()) {
Assert.assertNotNull(entry.getValue());
if (previous != null) {
Assert.assertTrue(entry.getValue().after(previous));
}
previous = entry.getValue();
}
}
Java 8を使用していますか? –
はい私は@FranciscoTena – user2298581
ですが、同じ最大日付のキーのリストが必要ですか? –