The only way I see is putting the condition in the map call. If you use filter you lose the "else" part.

List<String> myList = source.stream()
            .map(item -> {
                  if (!(item.get(bar) instanceof JSONObject)) {
                      return item.get(bar).toString();
                  } else {
                      return item.getJSONObject(attribute).get("key").toString();
                  }
            })
            .collect(Collectors.toList());

or, as Holger suggested in a comment, use the ternary conditional operator:

List<String> myList = source.stream()
            .map(i -> (i.get(bar) instanceof JSONObject ? i.getJSONObject(attribute).get("key") : i.get(bar)).toString())
            .collect(Collectors.toList());
Answer from Eran on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › java list › copy a list to another list in java
Copy a List to Another List in Java | Baeldung
2 weeks ago - List<Flower> flowers = Optional.ofNullable(list) .map(List::stream).orElseGet(Stream::empty) .skip(1) .collect(Collectors.toList()); Finally, one of the last Java versions allows us to create an immutable List containing the elements of the given Collection: List<T> copy = List.copyOf(list); The only conditions are that the given Collection mustn’t be null, or contain any null elements. In this article, we learned various ways to copy a List to another List with different Java versions.
🌐
Baeldung
baeldung.com › home › java › java collections › java map › combining two lists into a map in java
Combining Two Lists Into a Map in Java | Baeldung
June 27, 2025 - We then iterate through each element in KEY_LIST using a for loop, and for each element, we retrieve the corresponding element from VALUE_LIST using the same index i. Then, the put() method fills the key-value pair into the result map. Stream API provides many concise and efficient ways to manipulate Java collections.
🌐
GeeksforGeeks
geeksforgeeks.org › java › conversion-of-java-maps-to-list
Conversion of Java Map to List - GeeksforGeeks
July 11, 2025 - In Java, a Map is a collection that maps keys to values and a list is an ordered collection of objects and the List can contain duplicate values. There are some scenarios where we need to convert a Map into a List.
Top answer
1 of 1
1

I'd say, this is the canonical approach. No separate needs to be created, further operations like filter can be added. Still that's a matter of taste, I guess.

List<PhoneType> phoneTypes = phones.stream()
  .map(p -> new PhoneType(p.getId(), p.getType())))
  .collect(Collectors.toList());

There's a number of possibilities listed below with empirical test results gathered on an 8 core/8Gb machine, 4Gb JVM heap size. If there's a certain takeaway from that, it's, that differences don't range in orders of magnitude, with collection.foreach perhaps coming out somehow ahead of everything else. Find another similar discussion here, measuring further variations including iterators and arriving at similar conclusions.

As for the different approaches: stream.forEach() doesn't preserve the order of the input, everything else does, here's a detailed discussion of stream vs collections.

The first way mentioned above disqualifies because of parallelStream, it proves to be consistently slower in the case of a simple map operation.

The second, because collection.forEach does the same job, preserves the order and is faster too. At this occasion, without tapping into heavily mined ideological terrain, I'd like to hint at a discussion whether premature optimization is the root of all evil or not.

An intermediate version would be collection.forEach instead of stream().forEach, still I find it less appealing to look at than stream().map, some performance gain seems to be there, is not huge though, which has to we weighed against aesthetical drawbacks. A matter of taste perhaps.

One could choose to operate with for-loops and arrays only, circumventing collections and streams altogether. Drawback is, they come in fixed length only and look messy compared to the slick functional versions.

I made a series of test runs, find the results below, where surprisingly collection.foreach came out ahead, followed by the loop versions and the stream versions last, with parallelStream running slowest. The test results are blurred by factors I can't precisely pin down, garbage collection being the main suspect.

You can find code and data producing these results in a gist.

I did 10 runs, in each one running mappings for list/array sizes of 100000,1000000,10000000,20000000 and 30000000.

Before each run a warmup run with 30000000 which was not measured. Still there were random outliers scattered all over the place (kind of 17 seconds at an average of 1.5), I'd blame it on the garbage collector. For the final calculation of the averges I replaced the outliers with the average of the column (including the outlier)

loop:array→array    1.8
loop:array→list     0.983
collection.foreach  0.8
stream.foreach      1.3
mapSeq              1.8
mapParallel         2.1
🌐
Stack Abuse
stackabuse.com › java-convert-map-to-list
Java 8: How to Convert a Map to List
October 10, 2023 - A Java Map implementation is an collection that maps keys to values. Every Map Entry contains key/value pairs, and every key is associated with exactly one value.
🌐
Coderanch
coderanch.com › t › 755986 › java › Create-Map-existing-List-Entry
Create a Map out of existing List of Entry (Java in General forum at Coderanch)
November 28, 2022 - Not sure how this can be done as I am new to this forum and I just pasted my code from my Eclipse and then put it under Code. And finally added problem description. Anyway, here is what I have: List<Map.Entry<String, String>> Eg: 'One', 'Sunday' 'One', 'Monday' 'One', 'Tuesday' 'Two', 'Wednesday' 'Two', 'Thursday' 'Three', 'Friday' And here is what I want: Map<String, List<String>> Eg: 'One' -> 'Sunday', 'Monday', 'Tuesday' 'Two' -> 'Wednesday', 'Thursday' 'Three' -> 'Friday' Hope the above helps
🌐
LinkedIn
linkedin.com › pulse › how-map-reduce-items-from-list-java-helber-belmiro
How to Map and Reduce Items From a List in Java
October 6, 2021 - @Test void getTotalPrice() { List<Order> orders = createOrders(); OrderMapReducer orderMapReducer = new OrderMapReducer(); assertEquals(new BigDecimal(17800), orderMapReducer.getTotal(orders)); } private static List<Order> createOrders() { var strato = new Product("Fender", "Stratocaster", new BigDecimal(3500)); var sg = new Product("Gibson", "SG", new BigDecimal(4800)); var lesPaul = new Product("Gibson", "Les Paul", new BigDecimal(4500)); var rr = new Product("Jackson", "RR", new BigDecimal(5000)); return List.of( new Order("David Gilmour", List.of(strato)), new Order("Toni Iommi", List.of(s
Find elsewhere
🌐
How to do in Java
howtodoinjava.com › home › collections framework › convert list to map in java: tomap(), duplicate keys and order
Convert List to Map in Java: toMap(), Duplicate Keys and Order
September 23, 2022 - We cover the loop version, toMap() with duplicate keys, ordering and null values, grouping, and the Apache Commons and Guava helpers. A List keeps elements in order and allows duplicates, whereas a Map stores key-value pairs with unique keys and allows duplicate values.
🌐
TechWasti
techwasti.com › java-stream-api-convert-list-of-objects-to-another-list-of-objects-using-java-streams
stream API, covert one list of object to another - TechWasti
March 23, 2023 - Interactive simulators, cheat sheets, flashcards, and 2-minute tips for Software Engineers and Architects.
🌐
Medium
medium.com › codex › the-different-ways-to-copy-list-to-another-in-java-8db4ead985d8
5 Different Ways To Copy List To Another In Java | by Deddy Tandean | CodeX | Medium
August 21, 2021 - So, in this article, I will be talking about List, especially how to copy one List to another List. What is a List? A List is an ordered collection of objects in which duplicate values are allowed to be stored. It also preserves insertion order. There are multiple ways on how to copy a list to another list.
🌐
Java67
java67.com › 2019 › 12 › how-to-convert-map-to-list-in-java-8.html
3 Examples to convert a Map to List in Java 8 - Example Tutorial | Java67
In reality, it's not really possible to convert a Map to a List because both are different types of data structures. A Map is a collection of key-value pairs while a List contains just elements.
Top answer
1 of 8
227

Don't worry about any performance differences, they're going to be minimal in this case normally.

Method 2 is preferable because

  1. it doesn't require mutating a collection that exists outside the lambda expression.

  2. it's more readable because the different steps that are performed in the collection pipeline are written sequentially: first a filter operation, then a map operation, then collecting the result (for more info on the benefits of collection pipelines, see Martin Fowler's excellent article.)

  3. you can easily change the way values are collected by replacing the Collector that is used. In some cases you may need to write your own Collector, but then the benefit is that you can easily reuse that.

2 of 8
59

I agree with the existing answers that the second form is better because it does not have any side effects and is easier to parallelise (just use a parallel stream).

Performance wise, it appears they are equivalent until you start using parallel streams. In that case, map will perform really much better. See below the micro benchmark results:

Benchmark                         Mode  Samples    Score   Error  Units
SO28319064.forEach                avgt      100  187.310 ± 1.768  ms/op
SO28319064.map                    avgt      100  189.180 ± 1.692  ms/op
SO28319064.mapWithParallelStream  avgt      100   55,577 ± 0,782  ms/op

You can't boost the first example in the same manner because forEach is a terminal method - it returns void - so you are forced to use a stateful lambda. But that is really a bad idea if you are using parallel streams.

Finally note that your second snippet can be written in a sligthly more concise way with method references and static imports:

myFinalList = myListToParse.stream()
    .filter(Objects::nonNull)
    .map(this::doSomething)
    .collect(toList()); 
🌐
TutorialsPoint
tutorialspoint.com › java-program-to-convert-the-contents-of-a-map-to-list
Java program to convert the contents of a Map to list
May 31, 2024 - Create an ArrayList of String type to hold the values of the map. In its constructor call the method values() of the Map class. Print the contents of both lists. import java.util.HashMap; import java.uitl.ArrayList; import java.util.Map; public ...
🌐
Blogger
javarevisited.blogspot.com › 2016 › 04 › 10-examples-of-converting-list-to-map.html
10 Examples of Converting a List to Map in Java 8
Hello guys, suppose you have a list of objects, List and you want to convert that to a Map, where a key is obtained from the object and value is the object itself, how do you do it by using Java 8 stream and lambda expression? Prior to Java 8, you can do this by iterating through the List and populating the map by keys and values.