I want to sort LinkedHashMap that has LinkedList<Integer>
as key and float[]
as value.
For example let's say I have such LinkedHashMap like this:
LinkedHashMap<LinkedList<Integer>, float[]> hm = new LinkedHashMap<>();
LinkedList<Integer> linkedlist;
linkedlist = new LinkedList<>();
linkedlist.add(10);
linkedlist.add(7);
hm.put(linkedlist, new float[]{0.14f, 1.2f, 85.01f});
linkedlist = new LinkedList<>();
linkedlist.add(0);
linkedlist.add(41);
hm.put(linkedlist, new float[]{10.3f, 50.05f, 9.9f});
linkedlist = new LinkedList<>();
linkedlist.add(210);
linkedlist.add(3);
hm.put(linkedlist, new float[]{17.0f, 4.0f, 2.1f});
Now what I want is the output to be:
{0, 41}, {10.3f, 50.05f, 9.9f}
{10, 7}, {0.14f, 1.2f, 85.01f}
{210, 3}, {17.0f, 4.0f, 2.1f}
But when I use suggested solution (suggested by some of you in the comments section saying it is duplicate of another post that already have the right answer - the one below, link to it here) where it created new LinkedHashMap (cos I do not know how to sort the original LinkedHashMap in place by this code, unfortunately) like this:
LinkedHashMap<LinkedList<Integer>, float[]> sortedMap = new LinkedHashMap<>();
hm.entrySet()
.stream()
.sorted(Map.Entry.comparingByKey())
.forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));
hm = sortedMap;
My NetBeans 8.0.2 show me error about the line .sorted(Map.Entry.comparingByKey())
saying:
incompatible types: inference variable K has incompatible bounds
equality constraints: LinkedList<Integer>
upper bounds: Comparable <? super K>
where K,V are type-variables:
K extends Comparable<? super K> declared in method <K,V>comparingByKey()
V extends Object declared in method <K,V>comparingByKey()
I thought maybe for some reason the values in the LinkedList are wrong so I tested it like this and it shows those are all correct (I tested just first 50 entries as the list have hundreds of them):
for (int i = 0; i < hm.size(); i++) {
if (i < 50) {
for (Map.Entry<LinkedList<Integer>, float[]> entry : hm.entrySet()) {
LinkedList<Integer> k = entry.getKey();
System.out.println(k);
}
}
}