Seems that this is what you are after:

 customers.stream() 
          .filter(c -> c.getTrack() != null)
          .map(c -> c.getTrack().getId())
          .flatMap(id -> tracks.stream().filter(track -> Long.valueOf(track.getId()).equals(id)))
          .collect(Collectors.toSet());

Just note that for each id you are iterating the entire list of tracks; this has O(n*m) complexity. This is generally see as bad and you can improve it.

To make it better you would first create a HashSet of ids from Customer; having that HashSet you can now call contains on it with the ids you are interested in, since contains has a time complexity of O(1) (it's really called amortized complexity of O(1)). So now your complexity becomes O(n) + O(1), but since O(1) is a constant, it's really O(n) - much better that what you had before. In code:

Set<Long> set = customers.stream()
            .filter(c -> c.getTrack() != null)
            .map(c -> c.getTrack().getId())
            .collect(Collectors.toSet());

Set<CusomerTrack> tracksToSave = tracks.stream()
            .filter(track -> set.contains(track.getId())
            .collect(Collectors.toSet()));
Answer from Eugene on Stack Overflow
๐ŸŒ
Davidvlijmincx
davidvlijmincx.com โ€บ home โ€บ java โ€บ java stream join lists
Java Stream join lists
March 10, 2022 - The easiest way to join two lists with Streams is by using the Stream.concat(Stream a, Stream b) method. The method takes two Stream instances as parameters and puts the second Stream behind the first Stream.
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ java โ€บ examples โ€บ join two lists
Java Program to Join Two Lists
December 16, 2024 - Combining two lists in Java can be achieved through straightforward loops, utility methods like addAll(), or using the powerful Stream API for more complex and flexible operations.
๐ŸŒ
Javadeveloperzone
javadeveloperzone.com โ€บ java-basic โ€บ java-stream-of-multiple-lists
Java Stream of Multiple Lists โ€“ Java Developer Zone
So, this article is going to show ... interface) with an example. Stream.concat() is a static method, it combines two given streams into one logical stream of all elements of the first list followed by all elements of the second list....
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java list โ€บ iterate through two arraylists simultaneously
Iterate Through Two ArrayLists Simultaneously | Baeldung
April 3, 2025 - The BiFunction we provide as the third parameter, after the two Streams of our input lists, is used to create the elements of the Stream that we can then collect at the end to a single list that contains the right pairings. We should note that this method has all the benefits of Java Streams, including filtering and mapping the input data, filtering the output data, and keeping as little as possible in memory.
๐ŸŒ
Educative
educative.io โ€บ answers โ€บ how-to-merge-two-lists-in-java
How to merge two lists in Java
In this shot, we have seen how to merge two lists in Java by using the addAll() method and Java Stream.
๐ŸŒ
Techie Delight
techiedelight.com โ€บ home โ€บ java โ€บ join two lists in java
Join two lists in Java | Techie Delight
July 7, 2026 - This method is similar to List.addAll() but likely to run significantly faster. We can also use Java 8 Stream to join two lists. โฎš Using Stream.of() with flatMap() + Collector ยท Here weโ€™re obtaining a stream consisting of elements from both the list using the static factory method Stream.of() and accumulating all elements into a new list using a Collector.
Find elsewhere
Top answer
1 of 5
9

Can we collect two lists from Java 8 streams?

You cannot but if you have a way to group elements of the Lists according to a condition. In this case you could for example use Collectors.groupingBy() that will return Map<Foo, List<Bar>> where the values of the Map are the two List.

Note that in your case you don't need stream to do only filter.

Filter the invalid list with removeIf() and add all element of that in the first list :

invalidList.removeIf(o -> conditionToRemove);
goodList.addAll(invalidList);      

If you don't want to change the state of goodList you can do a shallow copy of that :

invalidList.removeIf(o -> conditionToRemove);
List<Foo> terminalList = new ArrayList<>(goodList);
terminalList.addAll(invalidList);
2 of 5
9

One way using Java 8 streams API is to use the Collectors.partitioningBy collector.

Consider I have a List of String elements: the input list has strings with various lengths; only strings with length 3 are valid.

List<String> input = Arrays.asList("one", "two", "three", "four", "five");
Map<Boolean, List<String>> map =
        input.collect(Collectors.partitioningBy(s -> s.length() == 3));
System.out.println(map); // {false=[three, four, five], true=[one, two]}

List<String> valid = map.get(true);    // [one, two]
List<String> invalid = map.get(false); // [three, four, five]

The resulting Map has only two records; one with valid and the other with not-valid input list elements. The map record with key=true has the valid string as a List: one, two. The other is a key=false and the not-valid strings: three, four, five.

Note that Collectors.partitioningBy produces always two records in the resulting map irrespective of the existence of valid or not-valid values.

๐ŸŒ
Javaprogramto
javaprogramto.com โ€บ 2020 โ€บ 11 โ€บ java-join-two-lists.html
How To Join Two Or Combine More Lists In old and new Java 8 Steam API? JavaProgramTo.com
November 15, 2020 - First, convert the List into Stream using steam() method and call Stream.concat() method to merge two streams. Finally, call Collectors.toList() method to convert Stream to List. import java.util.ArrayList; import java.util.List; import ...
๐ŸŒ
Medium
samedesilva.medium.com โ€บ verify-two-lists-using-java-using-stream-c68ebe523f64
Verify Two lists using Java using stream | by Sameera De Silva | Medium
January 4, 2023 - String fruitSaladWithCommas="Banana,Avacado,Pineapple,Apple,Orange,Mango"; List<String> fruitSaladList = Stream.of(fruitSaladWithCommas.split(",")).map(String::trim).collect(Collectors.toList()); // Then check that actual actualRecipientList contains all the expectedRecipientList boolean allExpectedRecipientsFound = fruitSaladList.containsAll(fruitsList); Assert.assertEquals(true, allExpectedRecipientsFound, "All the Fruits were not found in fruit Salad."); // ways to iterate though a list. https://crunchify.com/how-to-iterate-through-java-list-4-way-to-iterate-through-loop/ // Simple For loop System.out.println("==============> 1.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java list โ€บ intersection of two lists in java
Intersection of Two Lists in Java | Baeldung
April 4, 2025 - Well, as long as we follow Javaโ€™s conventions, the solution with stream methods will work fine for our custom class. How does the contains method decide whether a specific object appears in a list? Based on the equals method. Thus, we have to override the equals method and make sure that it compares two objects based on the values of the relevant properties.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java collections โ€บ java โ€“ combine multiple collections
Java - Combine Multiple Collections | Baeldung
May 11, 2024 - Initially, you get a Stream whose elements are the two collections, and then you flatten the Stream before collecting it into a merged list: Stream<String> combinedStream = Stream.of(collectionA, collectionB) .flatMap(Collection::stream); ...
๐ŸŒ
Medium
medium.com โ€บ @arunvincily โ€บ concatenate-two-lists-using-java-stream-9dfd2393246d
concatenate two lists using Java Stream - Arunvincily - Medium
March 14, 2025 - import java.util.Arrays; import ... // Concatenate two lists using Stream List<String> combinedList = Stream.concat(list1.stream(), list2.stream()) .collect(Collectors.toList()); // Output the combined list System.out.pri...
๐ŸŒ
YouTube
youtube.com โ€บ watch
Java 8 Stream API Interview Questions: Merge Two Lists using ...
To learn more, please visit the YouTube Help Center: https://www.youtube.com/help
Top answer
1 of 3
1

There are still some things unclear. Like why you are insisting on creating that SimpleDateFormat instance that you are not using anywhere. Or whether there is a significance in calling getCreatedBy() multiple times. Assuming that it is not necessary, the following code is equivalent

baseManager.findObjectsByNamedQuery(Class1.class, "Class1.findAll", new Object[]{})
    .stream()
    .map(item -> item.getCreatedBy())
    .map(createdBy -> Json.createObjectBuilder()
        .add("createdBy", createdBy)
        .add("phone", baseManager.findObjectsByNamedQuery(
            Class2.class, "Class2.findByCreatedBy", new Object[] {createdBy})
            .get(0).getPhone())
    )
    .forEach(jpb -> groupsBuilder.add(jpb));

Itโ€™s still unclear to me whether (or why) findObjectsByNamedQuery is not a varargs method. It would be quite natural to be a varargs method, not requiring these explicit new Object[] { โ€ฆ } allocations.

2 of 3
0

With pure Java8 Stream API:

public void convertItemsToJSon(List<Item> items) {
    ...
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    Map<Item, List<Class2>> sqlItems = items
            .stream()
            .collect(Collectors.toMap(Function.identity(), (item) -> baseManager.findObjectsByNamedQuery(Class2.class, "Class2.findByCratedBy", new Object[]{item.getCreatedBy()})));

    sqlItems.entrySet()
            .stream()
            .map(sqlItem -> buildJson(sqlItem.getKey(), sqlItem.getValue()))
            .forEach(groupsBuilder::add);
    ...
}

private JsonObjectBuilder buildJson(Item item,  List<Class2> class2Items) {
    return Json.createObjectBuilder().add("createdBy", item.getCreatedBy());
}

With StreamEx library

public void convertItemsToJSonStreamEx(List<Item> items) {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    ...
    StreamEx.of(items)
            .cross(item -> baseManager.findObjectsByNamedQuery(Class2.class, "Class2.findByCratedBy", new Object[]{item.getCreatedBy()}).stream())
            .mapKeys(item -> Json.createObjectBuilder().add("createdBy", item.getCreatedBy()))
            .mapKeyValue(this::addField)
            .forEach(groupsBuilder::add);
    ...
}

private JsonObjectBuilder addField(JsonObjectBuilder json, Class2 class2) {
    // You logic how to convert class2 to field in JSON
    return json;
}
๐ŸŒ
Quora
quora.com โ€บ How-do-you-combine-multiple-lists-in-Java
How to combine multiple lists in Java - Quora
Answer (1 of 4): Java 8 Stream API provides a couple of different options to join multiple lists. 1. 1. Joining List Using Java 8 Stream flatMap method In case we have a number of lists, we can use [code ]flatMap()[/code] method to join multiple lists in Java.flatMap method will return a Stream...
๐ŸŒ
Vultr Docs
docs.vultr.com โ€บ java โ€บ examples โ€บ merge-two-lists
Java Program to Merge two lists | Vultr Docs
December 16, 2024 - This code initially creates two lists, list1 and list2, and then merges them into mergedList. The addAll() method from the ArrayList class is used to add all elements from list2 to mergedList which already contains the elements from list1.