Yes, you can map each entry to another temporary entry that will hold the key and the parsed integer value. Then you can filter each entry based on their value.

Map<String, Integer> output =
    input.entrySet()
         .stream()
         .map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), Integer.valueOf(e.getValue())))
         .filter(e -> e.getValue() % 2 == 0)
         .collect(Collectors.toMap(
             Map.Entry::getKey,
             Map.Entry::getValue
         ));

Note that I used Integer.valueOf instead of parseInt since we actually want a boxed int.


If you have the luxury to use the StreamEx library, you can do it quite simply:

Map<String, Integer> output =
    EntryStream.of(input).mapValues(Integer::valueOf).filterValues(v -> v % 2 == 0).toMap();
Answer from Tunaki on Stack Overflow
Top answer
1 of 6
83

Yes, you can map each entry to another temporary entry that will hold the key and the parsed integer value. Then you can filter each entry based on their value.

Map<String, Integer> output =
    input.entrySet()
         .stream()
         .map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), Integer.valueOf(e.getValue())))
         .filter(e -> e.getValue() % 2 == 0)
         .collect(Collectors.toMap(
             Map.Entry::getKey,
             Map.Entry::getValue
         ));

Note that I used Integer.valueOf instead of parseInt since we actually want a boxed int.


If you have the luxury to use the StreamEx library, you can do it quite simply:

Map<String, Integer> output =
    EntryStream.of(input).mapValues(Integer::valueOf).filterValues(v -> v % 2 == 0).toMap();
2 of 6
19

One way to solve the problem with much lesser overhead is to move the mapping and filtering down to the collector.

Map<String, Integer> output = input.entrySet().stream().collect(
    HashMap::new,
    (map,e)->{ int i=Integer.parseInt(e.getValue()); if(i%2==0) map.put(e.getKey(), i); },
    Map::putAll);

This does not require the creation of intermediate Map.Entry instances and even better, will postpone the boxing of int values to the point when the values are actually added to the Map, which implies that values rejected by the filter are not boxed at all.

Compared to what Collectors.toMap(…) does, the operation is also simplified by using Map.put rather than Map.merge as we know beforehand that we don’t have to handle key collisions here.

However, as long as you don’t want to utilize parallel execution you may also consider the ordinary loop

HashMap<String,Integer> output=new HashMap<>();
for(Map.Entry<String, String> e: input.entrySet()) {
    int i = Integer.parseInt(e.getValue());
    if(i%2==0) output.put(e.getKey(), i);
}

or the internal iteration variant:

HashMap<String,Integer> output=new HashMap<>();
input.forEach((k,v)->{ int i = Integer.parseInt(v); if(i%2==0) output.put(k, i); });

the latter being quite compact and at least on par with all other variants regarding single threaded performance.

🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › stream › Stream.html
Stream (Java Platform SE 8 )
July 21, 2026 - Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element. Each mapped stream is closed after its contents have been placed into this stream.
🌐
Baeldung
baeldung.com › home › java › java collections › java map › working with maps using streams
Working With Maps Using Streams | Baeldung
November 10, 2025 - ... The principal thing to notice is that Streams are sequences of elements which can be easily obtained from a Collection. Maps have a different structure, with a mapping from keys to values, without sequence.
🌐
GeeksforGeeks
geeksforgeeks.org › java › stream-map-java-examples
Stream map() in Java with examples - GeeksforGeeks
January 4, 2025 - Java Collection · Last Updated : 4 Jan, 2025 · Stream map(Function mapper) returns a stream consisting of the results of applying the given function to the elements of this stream.
🌐
Medium
medium.com › @gauravverma.career › mastering-the-map-operation-in-java-streams-d8c819ae9e4b
Mastering the map() Operation in Java Streams | by Gaurav Verma | Medium
December 7, 2025 - The map() operation is a core component of Java's Stream API (introduced in Java 8) that transforms each element of a stream by applying a given function. Think of it as taking an input value and "mapping" it to a new, transformed output value.
🌐
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.
Find elsewhere
🌐
JRebel
jrebel.com › blog › java-streams-in-java-8
Using Java Streams in Java 8 and Beyond | JRebel by Perforce
June 16, 2025 - Map: Transforms the stream elements into something else, it accepts a function to apply to each and every element of the stream and returns a stream of the values the parameter function produced.
🌐
Baeldung
baeldung.com › home › java › java collections › java map › flatten a stream of maps to a single map in java
Flatten a Stream of Maps to a Single Map in Java | Baeldung
July 6, 2024 - This method offers direct control ... expressive solution has become available. Using streams, we can seamlessly convert a list of maps into a single map....
🌐
Mkyong
mkyong.com › home › java8 › java 8 streams map() examples
Java 8 Streams map() examples | mkyong.com
April 3, 2017 - package com.mkyong.java8; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class TestJava8 { public static void main(String[] args) { List<String> alpha = Arrays.asList("a", "b", "c", "d"); //Before Java8 List<String> alphaUpper = new ArrayList<>(); for (String s : alpha) { alphaUpper.add(s.toUpperCase()); } System.out.println(alpha); //[a, b, c, d] System.out.println(alphaUpper); //[A, B, C, D] // Java 8 List<String> collect = alpha.stream().map(String::toUpperCase).collect(Collectors.toList()); System.out.println(collect); //[A, B, C, D] // Extra, streams apply to any data type.
🌐
Medium
medium.com › @AlexanderObregon › javas-stream-map-method-explained-df0d0d461d39
Java’s Stream.map() Method Explained | Medium
August 27, 2024 - At its core, the map() method relies on a functional interface called Function<T, R>. This interface represents a function that accepts one argument of type T and produces a result of type R. The map() method uses this function to apply a transformation to each element in the stream...
🌐
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 - 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.
🌐
Reddit
reddit.com › r/javahelp › need help with .stream().map and collectors.tomap()
r/javahelp on Reddit: Need help with .stream().map and Collectors.toMap()
November 14, 2021 -

So I have a Map <Long, Ingredient> normalMap and my method needs to first invert the keys&values and lastly return the map as Map <String, Long>

To invert the map I wrote the following code:

invertedMap = normalMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));

So far, so good.

Now I need to make my inverted Map return the Name of my Object as a String. Note: My Ingredient Object has a @ Override method which overrides the toString() method and basically return the getter method { this.getName(); }

So what my idea was to write the following code:

return invertedMap.entrySet().stream().collect(Collectors.toMap(Ingredient::toString, Function.identity()));

Unfortunately, this does not work. I'm googling and trying to find a solution and whenever I find something useful it creates new errors. Pls help.

Update: I managed to make it work using following code:

        Map<String, Long> ingToString = new HashMap<>();
        for (Map.Entry<Ingredient, Long> entry : invertedMap.entrySet())
        {
            Ingredient ing = entry.getKey();
            ingToString.put(entry.getKey().toString(), entry.getValue());
        }
        return ingToString;

But my question still is, what is the equivalent to this code but using .stream() ?

Top answer
1 of 3
3
So I have a Map normalMap and my method needs to first invert the keys&values and lastly return the map as Map Why not do both at the same time? return normalMap.entrySet().stream().collect(Collectors.toMap( e -> e.getValue().toString(), Map.Entry::getKey));
2 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
🌐
Coderanch
coderanch.com › t › 680277 › java › Creating-map-maps-list-Java
Creating a map of maps from a list using Java 8 streams [Solved] (Java in General forum at Coderanch)
Java in General · Lambdas and ... I also have a list<MonitoredData> filled with such objects. The idea is to create a Map<Long, Map<String, Long>> using a stream from the list of MonitoredData....
🌐
Quora
quora.com › Should-Java-Stream-and-map-be-used-to-perform-actions-with-side-effects
Should Java Stream and map() be used to perform actions with side-effects? - Quora
Answer (1 of 3): What are the effects you are thinking about? Java Stream seems to be missing in this regard, but still efforts need to be made to take out any effects out of the transformations (map, flatMap, filter), and that may need a case-by-case discussion. The ideal place for side effects ...
🌐
Coderanch
coderanch.com › t › 752066 › java › Stream-API-map-method-pass
What does the Stream API's map() method pass in? (Features new in Java 8 forum at Coderanch)
So the map() method has only one argument, and it's the Function<T, R>. Well, as a result, when I'm writing a lambda, it has to become an anonymous class with my custom implementation, and this implementation are passed into this method?
🌐
HowToDoInJava
howtodoinjava.com › home › java 8 › java stream map()
Java Stream map() with Examples - HowToDoInJava
August 26, 2023 - Java 8 Stream.map() converts Stream to Stream. For each object of type X, a new object of type Y is created and put in the new Stream.
🌐
W3Schools
w3schools.com › java › java_io_streams.asp
Java I/O Streams (Input/Output Streams)
Java I/O streams read and write bytes, letting you work with any kind of file.
🌐
Scaler
scaler.com › home › topics › java stream map()
Java Stream map() - Scaler Topics
June 22, 2024 - The Java 8 Stream's map() method simply takes a stream of type X and returns another stream of type Y by applying the mapper function on the input stream elements and producing new stream elements of another type.