$show=/label

Nested lists with streams in Java 8

SHARE:

A quick guide to working with nested lists with streams in java 8. Examples with forEach() and flatMap() method to flatten collections.

1. Overview

In this article, You're going to learn how to work with nested list with java 8 streams.

Java 8 Stream API is added with flatMap() method which has the capability to map + flatten into objects or actual values.

let us explore the more ways using flatMap() with the complex objects.

In our example, we are using List of objects but you can use List or Set implementations.

Nested lists with streams in Java 8


2. Flattening Complex Nested Lists with java 8 Streams


Creating a complex object.

class EmployeeFactory { private List<Employee> employees; public EmployeeFactory(List<Employee> employees) { this.employees = employees; } public List<Employee> getEmployees() { return employees; } public void setEmployees(List<Employee> employees) { this.employees = employees; } } class Employee { private int id; private String name; private List<Address> addresses; public Employee(int id, String name, List<Address> addresses) { this.id = id; this.name = name; this.addresses = addresses; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Address> getAddresses() { return addresses; } public void setAddresses(List<Address> addresses) { this.addresses = addresses; } } class Address { private String line1; private String line2; private String town; private String city; private String pincode; public Address(String line1, String line2, String town, String city, String pincode) { this.line1 = line1; this.line2 = line2; this.town = town; this.city = city; this.pincode = pincode; } public String getLine1() { return line1; } public void setLine1(String line1) { this.line1 = line1; } public String getLine2() { return line2; } public void setLine2(String line2) { this.line2 = line2; } public String getTown() { return town; } public void setTown(String town) { this.town = town; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getPincode() { return pincode; } public void setPincode(String pincode) { this.pincode = pincode; } }

Getting the list of cities names which pincodes has char "3" or "5".

This can be done easily with the Java 8 Stream API in simple way.

package com.javaprogramto.java8.streams.nested;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class NestedComplexLists {

    public static void main(String[] args) {

        List<Address> addresses = new ArrayList<>();
        addresses.add(new Address("Address 1 Line 1", "Address 1 Line 2", "Address 1  town", "Address 1 city", "12345"));
        addresses.add(new Address("Address 2 Line 1", "Address 2 Line 2", "Address 2 town", "Address 2 city", "22222"));
        addresses.add(new Address("Address 3 Line 1", "Address 3 Line 2", "Address 3 town", "Address 3 city", "33333"));

        Employee employee1 = new Employee(100, "Emp 1", addresses);

        List<Address> addresses2 = new ArrayList<>();

        addresses2.add(new Address("Address 4 Line 1", "Address 4 Line 2", "Address 4 town", "Address 4 city", "444444"));
        addresses2.add(new Address("Address 5 Line 1", "Address 5 Line 2", "Address 5 town", "Address 5 city", "55555"));
        addresses2.add(new Address("Address 6 Line 1", "Address 6 Line 2", "Address 6 town", "Address 6 city", "66666"));

        Employee employee12 = new Employee(101, "Emp 2", addresses2);
        List<Employee> empList = Arrays.asList(employee1, employee12);

        EmployeeFactory employeeFactory = new EmployeeFactory(empList);

        List<EmployeeFactory> employeeFactories = Arrays.asList(employeeFactory);
        List<String> citiesList = employeeFactories.stream()
                .flatMap(factory -> factory.getEmployees().stream())
                .flatMap(emp -> emp.getAddresses().stream())
                .filter(address -> (address.getPincode().indexOf("5") >= 0 || address.getPincode().indexOf("3") >= 0))
                .map(address -> address.getCity())
                .collect(Collectors.toList());

        System.out.println("Cities list : " + citiesList);

    }
}

Output:

Cities list : [Address 1 city, Address 3 city, Address 5 city]

3. Flattening Nested Collections with forEach() in Java (Merging)


package com.javaprogramto.java8.streams.nested;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FlattenCollectionExample {
    public static void main(String[] args) {

        List<List<String>> nestedCollection = new ArrayList<>();

        List<String> strList1 = Arrays.asList("List 1 Str 1", "List 1 Str 2", "List 1 Str 3");

        List<String> strList2 = Arrays.asList("List 2 Str 4", "List 2 Str 5");

        List<String> strList3 = Arrays.asList("List 3 Str 6", "List 3 Str 7", "List 3 Str 8", "List 3 Str 9");
        nestedCollection.add(strList1);
        nestedCollection.add(strList2);
        nestedCollection.add(strList3);

        List<String> flattenList = new ArrayList<>();

        nestedCollection.forEach(flattenList::addAll);

        System.out.println("Flatten List with forEach() : "+flattenList);

    }
}

Output:

Flatten List with forEach: [List 1 Str 1, List 1 Str 2, List 1 Str 3, List 2 Str 4, List 2 Str 5, List 3 Str 6, List 3 Str 7, List 3 Str 8, List 3 Str 9]

4. Flattening Nested Collections with flatMap() in Java (Merging)


The same above code can be rewritten with flatMap() method which flatten List into Strings.

List<String> flattenList = nestedCollection.stream().flatMap(list -> list.stream()).collect(Collectors.toList());

System.out.println("Flatten List with flatMap() : " + flattenList);

The output will be the same as the above section program.

5. Conclusion


In this article, You've seen how to flatten the Collection or List with Stream API.

Examples programs on forEach() and flatMap() method in java 8.

As usual, all the examples are over GitHub.

Ref


COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,14,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,80,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,30,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,3,Java Programs,77,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Matrix,5,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,10,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Nested lists with streams in Java 8
Nested lists with streams in Java 8
A quick guide to working with nested lists with streams in java 8. Examples with forEach() and flatMap() method to flatten collections.
https://1.bp.blogspot.com/-zrXTBq_Ne94/Xw35ZueR9cI/AAAAAAAAC1Y/i5IAjpgqJ3Me6sObpIN7NRAyFWL_k6GVACLcBGAsYHQ/w400-h204/Nested%2Blists%2Bwith%2Bstreams%2Bin%2BJava%2B8.png
https://1.bp.blogspot.com/-zrXTBq_Ne94/Xw35ZueR9cI/AAAAAAAAC1Y/i5IAjpgqJ3Me6sObpIN7NRAyFWL_k6GVACLcBGAsYHQ/s72-w400-c-h204/Nested%2Blists%2Bwith%2Bstreams%2Bin%2BJava%2B8.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/07/nested-lists-with-streams-in-java-8.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/07/nested-lists-with-streams-in-java-8.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content