gpa
gpa

Reputation: 2451

ConcurrentHashMap with parallel Streams to remove keys

I have following sequential code that removes entries from hash map using another list of keys. Map size can be 50-100k entries and Remove key list can be 2k - 10k. I am looking for solution using new java-8 streams...

    List<Long> removed = new ArrayList<Long>();
    for (Long k : removelist) {
        if (null != map.remove(k)) {
            removed.add(k);
        }
    }

Upvotes: 1

Views: 4175

Answers (1)

zapl
zapl

Reputation: 63955

A kind of direct translation is

List<Long> removed = removeList.parallelStream()
        .map(key -> map.remove(key) != null ? key : null)
        .filter(Objects::nonNull)
        .collect(Collectors.toList());

the map step maps from key to key if it could be removed, to null if not. nulls are then filtered.

A bit shorter by directly filtering for those keys that can be removed:

    List<Long> removed = removeList.parallelStream()
        .filter(key -> map.remove(key) != null)
        .collect(Collectors.toList());

or via the key set's remove method which returns a boolean and can therefore be used directly as Predicate

    List<Long> removed = removeList.parallelStream()
            .filter(map.keySet()::remove)
            .collect(Collectors.toList());

Upvotes: 5

Related Questions