Filtering a Map afterwards is not as bad as it seems, keep in mind that iterating over a Map does not imply the same cost as performing a lookup (e.g. hashing).

But instead of

Iterator<Map.Entry<Player, Double>> itr = map.entrySet().iterator();
while (itr.hasNext()) {
    if (itr.next().getValue() <= radiusSquared) {
        itr.remove();
    }
}

you may simply use

map.values().removeIf(value -> value <= radiusSquared);

Even if you insist on having it as part of the collect operation, you can do it as postfix operation:

Map<Player, Double> dists = str.collect(
    Collectors.collectingAndThen(Collectors.toMap(p->p, p->calculate(p)),
    map -> { map.values().removeIf(value -> value <= radiusSquared); return map; }));

Avoiding to put unwanted entries in the first place is possible, but it implies manually retracing what the existing toMap collector does:

Map<Player, Double> dists = str.collect(
    HashMap::new,
    (m, p) -> { double value=calculate(p); if(value > radiusSquared) m.put(p, value); },
    Map::putAll);
Answer from Holger on Stack Overflow
🌐
JRebel
jrebel.com › blog › using-java-stream-map-and-java-stream-filter
Using Java 8 Stream Map and Java 8 Stream Filter | JRebel
June 25, 2025 - Further in this post we'll show ... to top · The new java.util.stream package has been added to JDK which allows us to perform filter/map/reduce-like operations with the Java 8 collections stream....
Top answer
1 of 3
6

Filtering a Map afterwards is not as bad as it seems, keep in mind that iterating over a Map does not imply the same cost as performing a lookup (e.g. hashing).

But instead of

Iterator<Map.Entry<Player, Double>> itr = map.entrySet().iterator();
while (itr.hasNext()) {
    if (itr.next().getValue() <= radiusSquared) {
        itr.remove();
    }
}

you may simply use

map.values().removeIf(value -> value <= radiusSquared);

Even if you insist on having it as part of the collect operation, you can do it as postfix operation:

Map<Player, Double> dists = str.collect(
    Collectors.collectingAndThen(Collectors.toMap(p->p, p->calculate(p)),
    map -> { map.values().removeIf(value -> value <= radiusSquared); return map; }));

Avoiding to put unwanted entries in the first place is possible, but it implies manually retracing what the existing toMap collector does:

Map<Player, Double> dists = str.collect(
    HashMap::new,
    (m, p) -> { double value=calculate(p); if(value > radiusSquared) m.put(p, value); },
    Map::putAll);
2 of 3
3

Note that your old-style iterator-loop could be rewritten in Java-8 using Collection.removeIf:

map.values().removeIf(dist -> dist <= radiusSquared);

So it does not actually that bad. Don't forget that keySet() and values() are modifiable.

If you want to solve this using single pipeline (for example, most of the entries are to be removed), then bad news for you. Seems that current Stream API does not allow you to do this without explicit use of the class with pair semantics. It's quite natural to create a Map.Entry instance, though already existing option is AbstractMap.SimpleEntry which has quite long and unpleasant name:

str.map(player -> new AbstractMap.SimpleEntry(player, getDistance(player)))
   .filter(entry -> entry.getValue() > radiusSquared)
   .toMap(Entry::getKey, Entry::getValue);

Note that it's likely that in Java-9 there will be Map.entry() static method, so you could use Map.entry(player, getDistance(player)). See JEP-269 for details.

As usual my StreamEx library has some syntactic sugar to solve this problem in cleaner way:

StreamEx.of(str).mapToEntry(player -> getDistance(player))
                .filterValues(dist -> dist > radiusSquared)
                .toMap();

And regarding the comments: yes, toMap() collector uses one-by-one insert, but don't worry: bulk inserts to map rarely improve the speed. You even cannot pre-size the hash-table (if your map is hash-based) as you don't know much about the elements being inserted. Probably you want to insert a million of objects with the same key: allocating the hash-table for million entries just to discover that you will have only one entry after insertion would be too wasteful.

Discussions

10 Examples of Stream API in Java - count filter map distinct collect() Examples
It feels weird to see rx pearl diagrams used to describe non-reactive operations. Not wrong, but weird. More on reddit.com
🌐 r/coding
2
2
September 7, 2022
Java 8 Map, Filter, and Collect Examples - DZone Java
are people nowadays using these things over traditional loops, arrays etc? I am asking because I only know java 7 and currently on job hunt. More on reddit.com
🌐 r/java
21
22
June 23, 2018
Proposal for stream: a (casting) filter by class
It can be "simplified" with .filter(Circle.class::isInstance) and .map(Circle.class::cast) ;) More on reddit.com
🌐 r/java
8
5
October 12, 2016
[discussion] Abuse of java streams?
Check Effective Java. It has a really good chapter about abusing streams. More on reddit.com
🌐 r/java
158
126
February 1, 2024
🌐
Mkyong
mkyong.com › home › java8 › java 8 map filter examples
Java 8 Map filter examples | mkyong.com
March 13, 2024 - With Java 8, we can convert a Map.entrySet() into a stream, followed by a filter() and collect().
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › stream › Stream.html
Stream (Java Platform SE 8 )
July 21, 2026 - The following example illustrates ... We create a stream of Widget objects via Collection.stream(), filter it to produce a stream containing only the red widgets, and then transform it into a stream of int values representing the weight of each red widget....
🌐
Medium
medium.com › spring-boot › java-stream-operations-filter-map-reduce-and-collect-65a1287ac2e0
Java Stream Operations: Filter, Map, Reduce, and Collect | by Piyu Jain | JavaToDev | Medium
May 23, 2023 - For example, you can filter a stream ... elements using the reduce operation, and finally collect the results into a collection or a single value using the collect operation....
🌐
Djamware
djamware.com › post › java-streams-tutorial-filter-map-and-collect-explained
Java Streams Tutorial: Filter, Map, and Collect Explained – Djamware
September 11, 2025 - We focused on three of the most commonly used methods: filter() – to select elements that match specific conditions. map() – to transform elements into another form. collect() – to gather the processed results into collections or strings.
🌐
Medium
medium.com › javarevisited › how-to-use-streams-map-filter-and-collect-methods-in-java-1e13609a318b
How to use map, filter, and collect methods in Java Stream? Example Tutorial | by javinpaul | Javarevisited | Medium
January 25, 2024 - Similar to the map, the filter is also an intermediate operation which means you can call other Stream methods after calling the filter. The filter() the method is also lazy which means that it will not be evaluated until you call a reduction method, like collect, and it will stop as soon as it reaches the target. If you are not familiar with Stream behavior, I suggest you check out Learn Java Functional Programming with Lambdas & Streams by Rang Rao Karnam on Udemy, which explains Stream fundamentals in good detail.
Find elsewhere
🌐
WPI Computer Science
web.cs.wpi.edu › ~cs2102 › b15 › Labs › map-and-filter.html
Map, Filter, Lambdas and Java Streams
Java doesn’t provide filter and map directly on lists. Instead, these operations work on Streams, a special kind of data for collections of elements, designed to support maps and filters.
🌐
Baeldung
baeldung.com › home › java › java streams › java stream filter with lambda expression
Java Stream Filter with Lambda Expression | Baeldung
January 8, 2024 - List<Customer> customersWithValidProfilePhoto = customers .stream() .filter(c -> { try { return c.hasValidProfilePhoto(); } catch (IOException e) { //handle exception } return false; }) .collect(Collectors.toList()); If we need to throw an exception from our predicate, we can wrap it in an unchecked exception like RuntimeException. Alternatively, we can use the ThrowingFunction library. ThrowingFunction is an open source library that allows us to handle checked exceptions in Java functional interfaces.
🌐
Java Code Geeks
javacodegeeks.com › home › core java
Java 8 filter & map & collect & Stream Example - Java Code Geeks
May 21, 2018 - The filter() method is also lazy which means it will not be evaluated until you call a reduction method like collect and it will stop as soon as it reaches the target. You need a good example to understand a new concept and that’s why you ...
🌐
MangoHost
mangohost.net › mangohost blog › java stream api – filtering, mapping, and collecting
Java Stream API – Filtering, Mapping, and Collecting
August 3, 2025 - public class LogEntry { private LocalDateTime timestamp; private String level; private String message; private String ipAddress; // Constructor and getters omitted } // Analyze error logs from the last hour List<LogEntry> logs = getServerLogs(); LocalDateTime oneHourAgo = LocalDateTime.now().minusHours(1); Map<String, Long> errorsByIP = logs.stream() .filter(log -> log.getTimestamp().isAfter(oneHourAgo)) .filter(log -> "ERROR".equals(log.getLevel())) .collect(Collectors.groupingBy( LogEntry::getIpAddress, Collectors.counting() )); // Find top 5 error-prone IPs List<String> topErrorIPs = errorsByIP.entrySet().stream() .sorted(Map.Entry.<String, Long>comparingByValue().reversed()) .limit(5) .map(Map.Entry::getKey) .collect(Collectors.toList());
🌐
IONOS UK
ionos.co.uk › digital guide › websites › web development › java stream collect
How to use Java collect() to collect and process data
November 3, 2023 - Here we’ll explain their structure and how the Java collect() method can be used. A Stream Collector can be used to create a list, set, or map from a stream. A stream is a sequence of elements that are processed one after another.
🌐
Jonathon Henderson
jonathonhenderson.co.uk › 2023 › 07 › 14 › rusty-java-streams
Rusty Java Streams | Jonathon Henderson
July 14, 2023 - The predicate provided to filter in this example returns true if the item provided is an even number, and false otherwise. This has the effect of throwing away the values 1 and 3 when collecting the stream into a list. Let’s use what we have so far to do something a bit more interesting: List<Integer> result = Stream.of("Java", "Rust", "Go", "Scala") .map(language -> language.toUpperCase()) .filter(language -> language.contains("A")) .map(language -> language.length()) .collect(Collectors.toList()); assertEquals(List.of(4, 5), result);
🌐
javabullets
javabullets.com › home » › java » › java 8 – streams cookbook
Java 8 – Streams Cookbook
August 22, 2017 - Summary Of Streams Streams in Java 8 provide a declarative approach to Collections.
🌐
Roy Tutorials
roytuts.com › home › java › java 8 stream filter example
Java 8 Stream Filter Example - Roy Tutorials
August 22, 2022 - The filter() method in Java 8 or onward is used to produce a stream containing only a certain type of objects into the result output and map() method is used to transform a stream from one type to another type into the result output.
🌐
Hedleyproctor
hedleyproctor.com › 2016 › 08 › java-8-streams-tutorial
Java 8 Streams Tutorial | Hedley Proctor
It takes a stream composed of Sets or another collection type, and “collapses” it down to a stream of the objects in the collections. Hence, to get a stream of all the jobs, we write: Stream<Job> jobs = claims.stream().map(Claim::getJobs).flatMap(Set::stream); Again, we can pipeline a number ...
🌐
Chrisdone
chrisdone.com › posts › stream-composability
Stream fusion and composability (Java 8 and Haskell) for newbies
public List<Article> getAllJavaArticles() { return articles.stream() .filter(article -> article.getTags().contains("Java")) .collect(Collectors.toList()); }
🌐
InformIT
informit.com › articles › article.aspx
Streams | 16.1 Introduction to Streams | InformIT
How to use map-reduce, filtering, flat mapping, and finishing adapters for downstream collectors · Understanding how to build and execute a parallel stream · Understanding factors that can affect parallel stream execution · Understanding the importance of benchmarking parallel stream execution · The Stream API brings a new programming paradigm to Java: a declarative way of processing data using streams—expressing what should be done to the values and not how it should be done.
🌐
amitph
amitph.com › home › java › using filter on stream of maps in java
Using Filter on Stream of Maps in Java - amitph
November 22, 2024 - We have used Java Streams to specify a predicate to filter Map elements and collect the filtered elements in a new HashMap or collect the filtered values into a List. We have also created a Java Stream based generic filter function that can ...
🌐
Roy Tutorials
roytuts.com › home
Map Archives - Roy Tutorials
In this example I am going to show you how to iterate over map of list of objects. Let’s say you have keys as strings and values as… ... Introduction In this tutorial, I will show you how you are going to collect and convert objects using lambda expression in Java 8 stream API. I will collect… ... Java 8 Filter This tutorial will show you how to use Java 8 stream API‘s filter() and map() methods.