如何从地图生成具有不同值的地图(并使用BinaryOperator使用右键)?]

问题描述 投票:12回答:5

我有一个映射Map<K, V>,我的目标是删除重复的值并再次输出完全相同的结构Map<K, V>。如果发现重复的值,则必须从保存这些值的两个键(kk1)中选择一个键(k1),因此,假定BinaryOperator<K>等于kk1k2中可用。

示例输入和输出:

// 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)的尝试有点

非常笨拙,并且包含诸如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 ); 调用中是否使用Collectors的适当组合(例如,没有可变操作的解决方案?

我有一个Map Map

,我的目标是删除重复的值并再次输出完全相同的结构Map 。如果发现重复的值,则必须选择一个...

java dictionary java-8 java-stream collectors
5个回答
11
投票
您可以使用Collectors

9
投票
尝试一下:简单的方法是将键和值取反,然后将Collectors.toMap收集器与合并功能一起使用。

3
投票
我发现非流解决方案更具表现力:

1
投票
我找到了一种只使用Map.merge的方式,无需收集并再次处理返回的Map。这个想法是:

1
投票
[通过“ Stream and Collectors.groupingBy”获得所需结果的另一种方法。
© www.soinside.com 2019 - 2024. All rights reserved.