Java stream api list to list

Java 8 — Stream FlatMap Example — List of Lists to List

The flatmap is an interesting concept of functional programming which allows you to flatten the list or stream apart from transforming it, just like the map does. This means you can use the flatmap to flatten the stream. If you have used the map() function from the Stream class before then you can use it to convert an object of type T to another object of Type S. For example, if you have a list of Authors then you can convert it to a List of books by transforming authors to books. FlatMap extends this idea, it not only transform one object to other it also flattens the list and that’s it’s very useful where you want to know about a combined data set.

For example, you have an Author object which holds a set of books and you have a list of authors. Now, you want to know all the books written by all these authors. You cannot combine the list of books from each other to get all the books because if you combine them you will get a list of List and not a single big list.

Читайте также:  Регулярное выражение поиск ссылок python

You need to use a flatMap function here to convert the Author to Book and also flatten two lists into one. That’s also the main difference between map and flatMap in Java 8.

Map function just transforms one object to another but flatmap both transforms and flattens the list, but it’s easier said than done. You won’t understand map and flatmap until you use them by yourself and that’s why I am going to show you two simple examples of flatMap function in Java 8.

These examples are very common e.g. convert a list of Lists into a single big list and will not only be useful in understanding how flatmap works but also in your day-to-day programming. Btw, if you haven’t started Java 8 yet, then you better first check these Java 8 Functional programming courses to get yourself familiar with essential Java 8 concepts like lambda expressions and Stream API.

Java 8 FlatMap Example 1 — list of Lists

This is one of the simplest examples of flatmap in Java 8. As I said before, flatMap can do two things, it can transform objects just like a map and it can also flatten a list or Stream. That’s why you can use it to convert a list of lists into just a list.

Java 8 - Stream FlatMap Example - List of Lists to List

In this program, I have three lists of numbers containing even numbers, odd numbers, and prime numbers. Now, I need just a list of numbers that contains all the numbers from the above lists.

For that, you can create a List of lists and add all those lists into that. After that, you can just use flatMap to flatten the list as shown below.

package tool; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; /** * * A simple Java Program to demonstrate how to * use flatMap function of Java 8. * * In this program, we'll convert a list of list * into just list of elements. */ public class Hello < public static void main(String[] args) < // list of even numbers List even = Arrays.asList( 2, 4, 6, 8, 10); // list of odd numbers List odd = Arrays.asList( 3, 5, 7, 9, 11); // list of prime numbers List primes = Arrays.asList(17, 19, 23, 29, 31); // list of numbers ListList> listOfNumbers = new ArrayList<>(); listOfNumbers.add(even); listOfNumbers.add(odd); listOfNumbers.add(primes); System.out.println("list of numbers: " + listOfNumbers); // above list is not really a list of numbers but a list of list // to convert that into a list of numbers we will use // the flatMap function List flattenedList = listOfNumbers.stream() .flatMap(l -> l.stream()) .collect(Collectors.toList()); System.out.println("list of numbers (flattend) : " + flattenedList); > > Output list of numbers: [[2, 4, 6, 8, 10], [3, 5, 7, 9, 11], [17, 19, 23, 29, 31]] list of numbers (flattend) : [2, 4, 6, 8, 10, 3, 5, 7, 9, 11, 17, 19, 23, 29, 31]

Java 8 Stream FlatMap Example 2

Here is another example to understand how the flatMap function works in Java 8 or when can you use it. In this case, we have an Author object which contains a set of books written by him.

In our application we have a list of such authors, we have two for simplicity, Joshua Bloch and Uncle Bob Martin. Now, I need all the books written by them. For this purpose, I can use the flatMap function.

First, I can get a stream of authors from the list then I can transform author to books by calling the getBook() method and flatten the list returned by this method.

The end result is a list of books. Since we don’t want duplicate books, I have collected the result in a Set by using the Collectors.toSet() method.

package tool; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** * * A simple Java Program to demonstrate how to use flatMap function of Java 8. * * In this program, we'll convert a set of authors into a set of books written by them. */ public class Hello < public static void main(String[] args) < ListlistOfAuthors = new ArrayList<>(); Author joshBloch = new Author("Joshua Bloch"); joshBloch.add("Effective Java"); joshBloch.add("Java Puzzlers");; Author uncleBob = new Author("Robert C. Martin"); uncleBob.add("Clean Code"); uncleBob.add("Clean Coder"); uncleBob.add("Clean Architecure"); listOfAuthors.add(joshBloch); listOfAuthors.add(uncleBob); SetString> books = listOfAuthors.stream() .flatMap(author -> author.getBooks().stream()) .collect(Collectors.toSet()); System.out.println("List of Books from all the authors"); System.out.println(books); > > class Author < private final String name; private final SetString> books; public Author(String name) < this.books = new HashSet<>(); this.name = name; > public void add(String book) < this.books.add(book); > public SetString> getBooks() < return books; > > Output: List of Books from all the authors [Java Puzzlers, Effective Java, Clean Code, Clean Coder, Clean Architecure]

You can see the final set contains all the books written by Joshua Bloch and Uncle Bob Martin including Effective Java and Clean Code, two of my favorite books.

Источник

How to convert list of object to another list object using streams?

The below code snippet, has been implemented without lambda expressions. How to implement the same functionality using lambda expressions?

public class Java8EmpTest < public static void main(String[] args) < // TODO Auto-generated method stub ListempInList = Arrays.asList(new Emp(1, 100), new Emp(2, 200), new Emp(3, 300)); List afterSalayHikeInJava7 = new ArrayList<>(); // old way for (Emp emp : empInList) < afterSalayHikeInJava7.add(new Emp(emp.getId(), emp.getSalary() * 100)); >afterSalayHikeInJava7.stream() .forEach(s -> System.out.println("Id :" + s.getId() + " Salary :" + s.getSalary())); > > class Emp < private int id; private int salary; public int getId() < return id; >Emp(int id, int salary) < this.id = id; this.salary = salary; >public int getSalary() < return salary; >> 

2 Answers 2

Simple use map() method in stream api and collect results:

 List employe = Arrays.asList(new Emp(1, 100), new Emp(2, 200), new Emp(3, 300)); List employeRise = employe.stream() .map(emp -> new Emp(emp.getId(), emp.getSalary * 100)) .collect(Collectors.toList()); employeRise.stream() .forEach(s -> System.out.println("Id :" + s.getId() + " Salary :" + s.getSalary())); 

map() each Emp of the input List to a new Emp and then collect() to a List :

List afterSalayHike = empInList.stream() .map(emp->new Emp(emp.getId(), emp.getSalary() * 100)) .collect(Collectors.toList()); 

Sorry for the offtopic but looks intresting. How does it looks like if you are using Java 9 flatMap() ?

Nevermind @Eran. I came across this question while I was looking for examples with flatMap and I did not know it was available in Java 8.

Источник

Knowledge Factory

Learn Java, Spring Boot, Quarkus, Kotlin, Go, Python, Angular, Vue.js, React.js, React Native, PHP, .Net and even more with CRUD example.

Java Stream API — How to convert List of objects to another List of objects using Java streams?

  • Get link
  • Facebook
  • Twitter
  • Pinterest
  • Email
  • Other Apps

Hello everyone, here we will show you how to convert a List of objects to another List of objects in Java using the Java streams map(). The ‘map’ method maps each element to its corresponding result.

Java Stream API

The Java Stream API provides a functional approach to processing collections of objects. The Stream in Java can be defined as a sequence of elements from a source Collection or Array. Most of the stream operations return a Stream. This helps create a chain of stream operations(stream pipe-lining). The streams also support the aggregate or terminal operations on the elements. for example, finding the minimum or maximum element or finding the average etc. Stream operations can either be executed sequentially or parallel. when performed parallelly, it is called a parallel stream.

Stream map() Method

The Java 8 Stream map() is an intermediate operation.It converts Stream to Stream. For each object of type obj1, a new object of type obj2 is created and put in the new Stream. The map() operation takes a Function, which is called for each value in the input stream and produces one result value, which is sent to the output stream. The stream map method takes Function as an argument that is a functional interface.

Convert List of User to List of UserDto

User.java

public class User
private String id;
private String name;
private String email;
private String phone;

public String getId()
return id;
>

public void setId(String id)
this.id = id;
>

public String getName()
return name;
>

public void setName(String name)
this.name = name;
>

public String getEmail()
return email;
>

public void setEmail(String email)
this.email = email;
>

public String getPhone()
return phone;
>

public void setPhone(String phone)
this.phone = phone;
>

public User(String id, String name,
String email, String phone)
super();
this.id = id;
this.name = name;
this.email = email;
this.phone = phone;
>

@Override
public String toString()
return "User [id background-color: white; font-family: "Droid Sans Mono", "monospace", monospace, "Droid Sans Fallback"; font-size: 15px; white-space: pre;"> ", name color: #a31515;">", email background-color: white; font-family: "Droid Sans Mono", "monospace", monospace, "Droid Sans Fallback"; font-size: 15px; white-space: pre;"> ", phone color: #a31515;">"]";
>
>

UserDto.java

public class UserDto
private String name;
private String email;
private String phone;

public String getName()
return name;
>

public void setName(String name)
this.name = name;
>

public String getEmail()
return email;
>

public void setEmail(String email)
this.email = email;
>

public String getPhone()
return phone;
>

public void setPhone(String phone)
this.phone = phone;
>

public UserDto(String name,
String email, String phone)
super();
this.name = name;
this.email = email;
this.phone = phone;
>

@Override
public String toString()
return "UserDto [name background-color: white; font-family: "Droid Sans Mono", "monospace", monospace, "Droid Sans Fallback"; white-space: pre;"> ", email background-color: white; font-family: "Droid Sans Mono", "monospace", monospace, "Droid Sans Fallback"; white-space: pre;"> ", phone color: #a31515;">"]";
>
>

Mapper.java

package java8.dev;

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

public class Mapper
private ListUser> users = new ArrayListUser>();

Mapper(ListUser> users)
this.users = users;
>

public ListUserDto> map()
ListUserDto> userDto = users.stream().
map(o -> new UserDto(o.getName(),
o.getEmail(), o.getPhone()))
.collect(Collectors.toList());

return userDto;

>
>

Driver.java

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

public class Driver
public static void main(String[] args)
User user = new User("1", "dummy",
"dummygmail@gmail.gmail", "!91-879");
User user1 = new User("2", "dummy2",
"dummygmail@gmail.gmail2", "!91-8792");
User user3 = new User("3", "dummy3",
"dummygmail@gmail.gmail3", "!91-87923");

ListUser> users = new ArrayListUser>();
users.add(user3);
users.add(user1);
users.add(user);

Mapper mapper = new Mapper(users);
System.out.println(mapper.map());
>
>

Output:

Another exampleConvert List of String to List of Integer in Java

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

public class Driver
public static void main(String[] args)
//Convert List of String to List of Integer in Java
ListString> list = Arrays.asList
( "8" , "7", "36", "2" );
ListInteger> intList = list.stream()
.map(s -> Integer.parseInt(s))
.collect(Collectors.toList());
System.out.println(intList);
>
>

Источник

Оцените статью