Ho una mappa Map<K, V>e il mio obiettivo è quello di rimuovere i valori duplicati e restituire la stessa struttura Map<K, V>. Nel caso in cui venga trovato il valore duplicato, deve essere selezionata una chiave ( k) tra le due chiavi ( k1e k1) che contengono questi valori, per questo motivo, assumono il BinaryOperator<K>dare kda k1ed k2è disponibile.
Esempio di input e output:
// 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
Il mio tentativo di utilizzo Stream::collect(Supplier, BiConsumer, BiConsumer)è un po ' goffo e contiene operazioni mutabili come Map::pute Map::removeche vorrei evitare:
// // 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
);
Esiste una soluzione che utilizza una combinazione appropriata Collectorsall'interno di una Stream::collectchiamata (ad esempio senza operazioni mutabili)?
Map::puto Map::removeall'interno di Collector.
BiMap. Forse un duplicato di Rimuovi valori duplicati da HashMap in Java
Streams?