I have to make sorted map which key is int[] and value is double. It cant be swapped because double will be duplicated. Moreover, map will be sort by value and last x values will be deleted.
I tried to make
Map<int[],Double> map = new TreeMap<>();;
int[] i = {0,1,1,0};
map.put(i,8.5); // ERROR HERE Organisms.java:46
i = new int[]{0,0,0,0};
map.put(i,30.0);
System.out.println("sorted" + sortByValue(map));
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: [I cannot be cast to java.lang.Comparable at java.util.TreeMap.compare(TreeMap.java:1294) at java.util.TreeMap.put(TreeMap.java:538) at com.pszt_organism.Organisms.test(Organisms.java:46) <-- MARKED ERROR
I found method sortByValue(Map<K, V> map)
in this topic: java8 example by Carter Page
I suppose that TreeMap has problem with sorting table of int. How to solve that?
EDIT:
private <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> 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
));
}
You don't need to use TreeMap
to use that sorting method. Just use a different Map
. That sorting method creates a new LinkedHashMap
for the result, so the Map
which is passed as an argument is just a temporary container.