使用泛型函数对基于ArrayList中索引的HashMap进行排序
问题描述:
所以我想对包含人名(键)及其年龄和高度(以cm为单位)的HashMap进行排序。 HashMap的设置是这样的:使用泛型函数对基于ArrayList中索引的HashMap进行排序
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);
然后,我想使用泛型函数对人物的高度进行排序。
这是我的尝试:
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;
}
但是我得到这个错误:
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>
我使用的基本功能是从这个线程:https://stackoverflow.com/a/2581754
这是功能:
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;
}
我一直试图让这个工作大约一个半小时,现在我几乎放弃了。请帮忙!
答
好的,就像在你的问题的评论中提到的那样,它不是一个真正的面向对象的方法
但是用泛型和lambdas来练习是很好的。
它会工作,当你还声明列表类型。
public static <K, V extends Comparable<? super V>> Map<K, List<V>> sortByValue(Map<K, List<V>> map) {
Map<K,List<V>> result = new LinkedHashMap<>();
Stream <Entry<K,List<V>>> st = map.entrySet().stream();
st.sorted(Comparator.comparing(e -> e.getValue().get(1)))
.forEach(e -> result.put(e.getKey(), e.getValue()));
return result;
}
或者,您也可以以这种方式使用的分类方法:
st.sorted((e1,e2)->{return e1.getValue().get(1).compareTo(e2.getValue().get(1));})
.forEach(e -> result.put(e.getKey(), e.getValue()));
而且随着检查结果:
result.forEach((name, list)-> System.out.println(""+name+":" + list.get(1).toString()));
我看到这一行,认为这将是一个很大更容易有高度和年龄的对象字段: l1.add(22); l1.add(177); //年龄和身高 – superbAfterSemperPhi 2014-12-04 23:06:17
您是否真的需要将年龄和身高放入一个普通的ArrayList中?这不是完全面向对象的。 – fjf2002 2014-12-04 23:06:34
所以我的第一个问题是为什么你需要按高度进行排序?就像你正在试图做一个打印语句,让高度达到最大值或最终情况是什么。有可能不得不排序列表 – Jay 2014-12-04 23:06:45