我有一个映射Map<K, V>
,我的目标是删除重复的值并再次输出完全相同的结构Map<K, V>
。如果发现重复的值,则必须从保存这些值的两个键(k
和k1
)中选择一个键(k1
),因此,假定BinaryOperator<K>
等于k
从k1
和k2
中可用。
示例输入和输出:
// Input
Map<Integer, String> map = new HashMap<>();
map.put(1, "apple");
map.put(5, "apple");
map.put(4, "orange");
map.put(3, "apple");
map.put(2, "orange");
// Output: {5=apple, 4=orange} // the key is the largest possible
非常笨拙,并且包含诸如Stream::collect(Supplier, BiConsumer, BiConsumer)
和Map::put
之类的可变操作,我想避免:]]我有一个Map MapMap::remove
[[在一个
// // the key is the largest integer possible (following the example above) final BinaryOperator<K> reducingKeysBinaryOperator = (k1, k2) -> k1 > k2 ? k1 : k2; Map<K, V> distinctValuesMap = map.entrySet().stream().collect( HashMap::new, // A new map to return (supplier) (map, entry) -> { // Accumulator final K key = entry.getKey(); final V value = entry.getValue(); final Entry<K, V> editedEntry = Optional.of(map) // New edited Value .filter(HashMap::isEmpty) .map(m -> new SimpleEntry<>(key, value)) // If a first entry, use it .orElseGet(() -> map.entrySet() // otherwise check for a duplicate .stream() .filter(e -> value.equals(e.getValue())) .findFirst() .map(e -> new SimpleEntry<>( // .. if found, replace reducingKeysBinaryOperator.apply(e.getKey(), key), map.remove(e.getKey()))) .orElse(new SimpleEntry<>(key, value))); // .. or else leave map.put(editedEntry.getKey(), editedEntry.getValue()); // put it to the map }, (m1, m2) -> {} // Combiner );
调用中是否使用Collectors
的适当组合(例如,没有可变操作的解决方案?
,我的目标是删除重复的值并再次输出完全相同的结构Map
Collectors
Map.merge
的方式,无需收集并再次处理返回的Map。这个想法是: