मेरे पास एक नक्शा है 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::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एक Stream::collectकॉल के भीतर एक उपयुक्त संयोजन का उपयोग करके एक समाधान है (जैसे कि बिना परिवर्तन योग्य संचालन)?
Map::putया Map::removeभीतर Collector।
BiMap। की शायद कोई डुप्लिकेट जावा में HashMap से निकालें डुप्लिकेट मानों
Stream?