我有一个名为Map<K, V>
的地图,我的目标是删除重复的值并输出完全相同的结构Map<K, V>
。如果找到重复的值,则必须从保存这些值的两个键(k1
和k2
)中选择一个键(k
),因此,假设可以使用BinaryOperator<K>
来从k1
和k2
中提供k
。
输入和输出示例:
// 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::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
);
是否可以在一个Stream::collect
调用中使用适当组合的Collectors
解决问题(例如,无需可变操作)?
Stream
完成吗? - Turing85Map::put
或Map::remove
。 - Nikolas CharalambidisBiMap
。可能是Remove duplicate values from HashMap in Java的副本。 - Naman