我正在使用Java 8编写一个通过值对映射进行排序的代码。
我已经完成了大部分工作,但是我不知道如何使用Java 8功能将列表转换为映射表。
public class SortMapByValue {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 3);
map.put("V", 1);
map.put("Anss", 9);
map.put("D", 5);
map.put("E", 2);
map.put("F", 10);
HashMap<String, Integer> newMap = new LinkedHashMap<>();
List<Map.Entry<String, Integer>> list = new ArrayList<>(map.entrySet());
Collections.sort(list, (o1, o2) -> o1.getValue() - o2.getValue());
// Need to this using Java 8 -- start
for (Entry<String, Integer> entry : list) {
newMap.put(entry.getKey(), entry.getValue());
}
// Need to this using Java 8 -- end
newMap.forEach((k, v) -> System.out.println("Key : " + k + " Value : " + v));
}
}
Entry::comparingByValue
- Eugene