1.【强制】关于 hashCode 和 equals 的处理,遵循如下规则:
Map<String, Object> map = new HashMap<>(16); if(map.isEmpty()) { System.out.println("no element in this map."); }
List<Pair<String, Double>> pairArrayList = new ArrayList<>(3); pairArrayList.add(new Pair<>("version", 12.10)); pairArrayList.add(new Pair<>("version", 12.19)); pairArrayList.add(new Pair<>("version", 6.28)); Map<String, Double> map = pairArrayList.stream().collect( // 生成的 map 集合中只有一个键值对:{version=6.28} Collectors.toMap(Pair::getKey, Pair::getValue, (v1, v2) -> v2));
Pair<T1, T2> 定义如下:
class Pair<T1, T2> { private T1 key; private T2 value; public Pair(T1 t11, T2 t22) { super(); this.key = t11; this.value = t22; } public T1 getKey() { return key; } public void setKey(T1 key) { this.key = key; } public T2 getValue() { return value; } public void setValue(T2 value) { this.value = value; } }
当这样写时,报错 java.lang.IllegalStateException: Duplicate key 12.1
Map<String, Double> map = pairArrayList.stream().collect(
Collectors.toMap(Pair::getKey, Pair::getValue));
String[] departments = new String[] {"iERP", "iERP", "EIBU"}; // 抛出 IllegalStateException 异常 Map<Integer, String> map = Arrays.stream(departments) .collect(Collectors.toMap(String::hashCode, str -> str));
原文:https://www.cnblogs.com/Vincent-yuan/p/14887602.html