So I'm trying to sort a HashMap that contains the person's name (key) and their age and height in cm. The HashMap is set up like this:
Map<String, List<Integer>> s = new HashMap<>();
List<Integer> l1, l2, l3, l4;
l1 = new ArrayList<>();
l2 = new ArrayList();
l3 = new ArrayList();
l4 = new ArrayList();
l1.add(22); l1.add(177); //age then height
l2.add(45); l2.add(162);
l3.add(19); l3.add(182);
l4.add(38); l4.add(174);
s.put("John", l1);
s.put("Eric", l2);
s.put("Darren", l3);
s.put("Carter", l4);
Then I want to sort the Map by the person's height using a generic function.
This is what I tried:
static <K, V extends List<? extends Comparable<? super V>>> Map<K, V> specialSort(Map<K, V> map) {
Map<K, V> result = new LinkedHashMap<>();
Stream<Entry<K, V>> st = map.entrySet().stream();
st.sorted(Comparator.comparing(e -> e.getValue().get(0))).
forEach(e -> result.put(e.getKey(), e.getValue()));
return result;
}
However I get this error:
incompatible types: inferred type does not conform to upper bound(s)
inferred: CAP#1
upper bound(s): Comparable<? super CAP#1>,V,Object
where V,K are type-variables:
V extends List<? extends Comparable<? super V>> declared in method <K,V>specialSort(Map<K,V>)
K extends Object declared in method <K,V>specialSort(Map<K,V>)
where CAP#1 is a fresh type-variable:
CAP#1 extends Comparable<? super V> from capture of ? extends Comparable<? super V>
The base function I'm using is from this thread: https://stackoverflow.com/a/2581754
This is the function:
public static <K, V extends Comparable<? super V>> Map<K, V>
sortByValue( Map<K, V> map )
{
Map<K,V> result = new LinkedHashMap<>();
Stream <Entry<K,V>> st = map.entrySet().stream();
st.sorted(Comparator.comparing(e -> e.getValue()))
.forEach(e ->result.put(e.getKey(),e.getValue()));
return result;
}
I've been trying to get this to work for about an hour and a half now and I've almost given up. Please help!