Since Java 8, there are some standard options to do this in JDK:

Collection<E> in = ...
Object[] mapped = in.stream().map(e -> doMap(e)).toArray();
// or
List<E> mapped = in.stream().map(e -> doMap(e)).collect(Collectors.toList());

See java.util.Collection.stream() and java.util.stream.Collectors.toList().

Answer from leventov on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Map.html
Map (Java Platform SE 8 )
3 weeks ago - remappingFunction - the function to recompute a value if present ... ClassCastException - if the class of the specified key or value prevents it from being stored in this map (optional) NullPointerException - if the specified key is null and this map does not support null keys or the value or remappingFunction is null ... Java™ Platform Standard Ed. 8...
🌐
Java67
java67.com › 2015 › 01 › java-8-map-function-examples.html
Java 8 Stream map() function Example with Explanation | Java67
By using the map() function, you can apply any function to every element of the Collection. It can be any predefined function or a user-defined function. You not only can use the lambda expression but also method references.
Discussions

Java: is there a map function? - Stack Overflow
I need a map function. Is there something like this in Java already? (For those who wonder: I of course know how to implement this trivial function myself...) More on stackoverflow.com
🌐 stackoverflow.com
Lambda expression java 8 map method - Stack Overflow
The syntax of map method in java 8 is : Stream map(Function p. More on stackoverflow.com
🌐 stackoverflow.com
Pass Java 8 streaming map function as a parameter - Stack Overflow
I have a string which is comma separated an I want to convert it to an array. However in some cases, I require integer parsing, sometimes double. Is there a way I can pass mapToDouble or mapToInt r... More on stackoverflow.com
🌐 stackoverflow.com
java - what does java8 stream map do here? - Stack Overflow
Performs the given action for each entry in this map until all entries have been processed ... Returns a stream consisting of the results of applying the given function to the elements of this stream. More on stackoverflow.com
🌐 stackoverflow.com
🌐
DZone
dzone.com › coding › languages › java 8 map, filter, and collect examples
Java 8 Examples: Map, Filter and Collect
June 21, 2018 - That's why we called the map() function first. Once we have the Stream of Integer, we can apply maths to find the even numbers. We passed that condition to filter method. If we needed to filter on String, e.g. select all string which has length > 2, then we would have called filter before map. That's all about how to use map and filter in Java 8.
🌐
GitHub
github.com › mtumilowicz › java8-map-functions
GitHub - mtumilowicz/java8-map-functions: Overview of Java 8 additions to Map interface.
extends V> mappingFunction) - If the specified key is not already associated with a value (or is mapped to null), attempts to compute its value using the given mapping function and enters it into this map unless null.
Author   mtumilowicz
🌐
Mkyong
mkyong.com › home › java8 › java 8 streams map() examples
Java 8 Streams map() examples - Mkyong.com
April 3, 2017 - 3.3 Java 8 example. , NowJava8 Class. // convert inside the map() method directly. List result = staff.stream().map(temp -> { StaffPublic obj = new StaffPublic(); obj.setName(temp.getName()); obj.setAge(temp.getAge()); if (“mkyong”.equals(temp.getName())) { obj.setExtra(“this field is for mkyong only!”); } return obj; }).collect(Collectors.toList()); System.out.println(result); the above function will nowhere return the output you have specified.
🌐
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.
Find elsewhere
🌐
LinkedIn
linkedin.com › pulse › how-safely-use-map-operation-java-8-streams-nikhil-gargatte
How to Safely Use the map() Operation in Java 8 Streams
May 11, 2023 - The map() operation in Java 8 streams transforms the elements of a collection based on a specified function. It takes a Function<T, R> as input, where T is the type of the input element and R is the type of the output element.
🌐
Medium
neesri.medium.com › what-is-map-in-java-8-f9f334367f58
What is map in java 8. In Java 8, the map method is part of… | by A cup of JAVA coffee with NeeSri | Medium
January 15, 2024 - In Java 8, the map method is part of the Stream API, and it is used for transforming each element of a stream using a given function. It applies the provided function to each element in the stream and produces a new stream of the transformed ...
🌐
Baeldung
baeldung.com › home › java › java collections › java map › working with maps using streams
Working With Maps Using Streams | Baeldung
November 10, 2025 - The article is an example-heavy introduction of the possibilities and operations offered by the Java 8 Stream API. ... 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.
🌐
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.
🌐
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 ...
🌐
GeeksforGeeks
geeksforgeeks.org › java › stream-map-java-examples
Stream map() in Java with examples - GeeksforGeeks
January 4, 2025 - // Java code for Stream map(Function mapper) // to get a stream by applying the // given function to this stream. import java.util.*; class GFG { // Driver code public static void main(String[] args) { System.out.println("The stream after applying " + "the function is : "); // Creating a list of Strings List<String> list = Arrays.asList("Geeks", "FOR", "GEEKSQUIZ", "Computer", "Science", "gfg"); // Using Stream map(Function mapper) and // displaying the length of each String list.stream().map(str -> str.length()).forEach(System.out::println); } } Output : The stream after applying the function is : 5 3 9 8 7 3 · Comment · Article Tags: Article Tags: Java ·
🌐
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 - That’s all about how to use map and filter in Java 8. We have seen an interesting example of how we can use the map to transform an object to another and how to use the filter to select an object-based upon condition.
Top answer
1 of 2
5

You can do it with a simple function that accepts String and a Function<String, T> that will convert every string element using this function. The good news is that this function may return any type you want: Integer, Double, BigDecimal, String or any other type you want. In below example I use a method reference like:

  • Integer::valueOf to convert elements to Integer values
  • Double::valueOf to convert elements to Double values
  • String::valueOf to convert elements to String values

Consider following example:

import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ParsingStringTest {

    public static void main(String[] args) {
        String str = "1, , 3, 4, 5, , 7, sasd, aaa, 0";

        List<Double> doubles = parse(str, Double::valueOf);
        List<Integer> integers = parse(str, Integer::valueOf);
        List<String> strings = parse(str, String::valueOf);

        System.out.println(doubles);
        System.out.println(integers);
        System.out.println(strings);

        Double[] array = doubles.toArray(new Double[doubles.size()]);

        System.out.println(Arrays.toString(array));
    }

    public static <T> List<T> parse(String str, Function<String, T> parseFunction) {
        return Arrays.stream(str.split(","))
                .filter(s -> !s.isEmpty())
                .map(s -> {
                    try {
                        return parseFunction.apply(s.trim());
                    } catch (Exception e) {}
                    return null;
                })
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
    }
}

Console output for following example is:

[1.0, 3.0, 4.0, 5.0, 7.0, 0.0]
[1, 3, 4, 5, 7, 0]
[1, , 3, 4, 5, , 7, sasd, aaa, 0]
[1.0, 3.0, 4.0, 5.0, 7.0, 0.0]

I hope it helps.

2 of 2
3

There is a way, but you wouldn't be working with primitives any more, because generics in Java doesn't support primitive types. Instead, you can use Integer and Double wrapper types:

public static <T> T[] convert(
        String test, 
        Function<String, T> parser,
        boolean condition, 
        T ifConditionTrue,
        T ifConditionFalse,
        IntFunction<T[]> arrayGenerator) {

    return Arrays.stream(test.split(","))
        .map(x -> {
            if (StringUtils.isEmpty(x)) {
                return condition ? ifConditionTrue : ifConditionFalse;
            }
            return parser.apply(x);
        })
        .toArray(arrayGenerator);
}

This method can be used as follows:

Integer[] ints = convert("1, ,3", Integer::parseInt, true, -1, 0, Integer[]::new);
🌐
Board Infinity
boardinfinity.com › blog › learn-about-map-stream-in-java
Map() Stream in Java with Example | Board Infinity
July 7, 2023 - Map is a higher-order function in java 8. It converts the elements of an object to another type of element. Stream is a data structure that provides a way to represent data on which one can perform sequential operations such as mapping and reducing.
Top answer
1 of 4
21
strings.stream().map(s->map.put(s, s));

does nothing, since the stream pipeline is not processed until you execute a terminal operation. Therefore the Map remains empty.

Adding a terminal operation to the stream pipeline will cause map.put(s, s) to be executed for each element of the Stream required by the terminal operation (some terminal operations require just one element, while others require all elements of the Stream).

On the other hand, the second stream pipeline:

strings.stream().forEach(s->map.put(s, s));

ends with a terminal operation - forEach - which is executed for each element of the Stream.

That said, both snippets are misusing Streams. In order to populate a Collection or a Map based on the contents of the Stream, you should use collect(), which can create a Map or a Collection and populate it however you like. forEach and map have different purposes.

For example, to create a Map:

List<String> strings = Lists.newArrayList("1", "2");
Map<String, String> map = strings.stream()
                                 .collect(Collectors.toMap(Function.identity(),
                                                           Function.identity()));
System.out.println(map);
2 of 4
9

The difference is this:

  • The idea of forEach() is to "work" on each element of the underlying collection (by having a side effect) whereas
  • map() is about applying a method on each object and putting the result of that into a new stream

That is also the reason why your stream().map() doesn't result in something - because you throw away the new stream created by the map() call!

In that sense, the signatures of the two methods tell you that:

void forEach(BiConsumer<? super K,? super V> action)

Performs the given action for each entry in this map until all entries have been processed

versus

 <R> Stream<R> map(Function<? super T,? extends R> mapper)

Returns a stream consisting of the results of applying the given function to the elements of this stream.

And for the record: only map() is a stream method - forEach() exists for both, streams and Collections/Iterables.

🌐
Javabrahman
javabrahman.com › java-8 › java-8-mapping-with-streams-map-flatmap-methods-tutorial-with-examples
Java 8 Mapping with Streams | map and flatMap methods ...
Lets see both of these methods in detail now. Definition & usage of map() method The map() method helps us transform one type of stream to another type of stream. Definition of map() method in java.util.stream.Stream&lt;T> is - <R> Stream<R> map(Function<? super T,? extends R> mapper) Where,
🌐
Novixys Software
novixys.com › blog › java-8-streams-map-examples
Java 8 Streams Map Examples | Novixys Software Dev Blog
January 5, 2018 - A part of Java 8 streams is the map() facility which can map one value to another in a stream. In this article, let us examine some common use cases where map() is useful. ... This complicated looking definition is stating that the map() method ...