2014-12-04 76 views
1

所以我想對包含人名(鍵)及其年齡和高度(以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; 
} 

我一直試圖讓這個工作大約一個半小時,現在我幾乎放棄了。請幫忙!

+0

我看到這一行,認爲這將是一個很大更容易有高度和年齡的對象字段: l1.add(22); l1.add(177); //年齡和身高 – superbAfterSemperPhi 2014-12-04 23:06:17

+2

您是否真的需要將年齡和身高放入一個普通的ArrayList中?這不是完全面向對象的。 – fjf2002 2014-12-04 23:06:34

+0

所以我的第一個問題是爲什麼你需要按高度進行排序?就像你正在試圖做一個打印語句,讓高度達到最大值或最終情況是什麼。有可能不得不排序列表 – Jay 2014-12-04 23:06:45

回答

0

好的,就像在你的問題的評論中提到的那樣,它不是一個真正的面向對象的方法
但是用泛型和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())); 
相關問題