Java stream add list to list

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);
>
>

Источник

Add Multiple Items to Java ArrayList

Learn to add multiple items to an ArrayList in a single statement using simple-to-follow Java examples.

1. Using List.of() or Arrays.asList() to Initialize a New ArrayList

To initialize an ArrayList with multiple items in a single line can be done by creating a List of items using either Arrays.asList() or List.of() methods. Both methods create an immutable List containing items passed to the factory method.

In the given example, we add two strings, “a” and “b”, to the ArrayList.

ArrayList arrayList = new ArrayList<>(Arrays.asList("a", "b")); //or ArrayList arrayList = new ArrayList<>(List.of("a", "b"));

2. Using Collections.addAll() to Add Items from an Existing ArrayList

To add all items from another collection to this ArrayList, we can use Collections.addAll() method that adds all of the specified items to the given list. Note that the items to be added may be specified individually or as an array.

ArrayList arrayList = new ArrayList<>(Arrays.asList("a", "b")); Collections.addAll(arrayList, "c", "d"); System.out.println(arrayList); //[a, b, c, d]

Alternatively, we can use ArrayList constructor that accepts a collection and initializes the ArrayList with the items from the argument collection. This can be useful if we add the whole collection into this ArrayList.

List namesList = Arrays.asList( "a", "b", "c"); ArrayList instance = new ArrayList<>(namesList);

3. Using Stream API to Add Only Selected Items

This method uses Java Stream API. We create a stream of elements from the first list, add a filter() to get the desired elements only, and then add the filtered elements to another list.

//List 1 List namesList = Arrays.asList( "a", "b", "c"); //List 2 ArrayList otherList = new ArrayList<>(Arrays.asList( "d", "e")); //Do not add 'a' to the new list namesList.stream() .filter(name -> !"a".equals(name)) .forEachOrdered(otherList::add); System.out.println(otherList); //[d, e, b, c]

In the above examples, we learned to add multiple elements to ArrayList. We have added all elements to ArrayList, and then we saw the example of adding only selected items to the ArrayList from the Java 8 stream API.

Источник

Collecting Stream Items into List in Java

Learn to collect the items from a Stream into a List using different ways in Java. We will compare these different techniques so we can decide the best way for any kind of scenario.

1. Different Ways to Collect Stream Items into List

There are primarily three ways to collect stream items into a list. Let’s compare them.

  • The toList() method has been added in Java 16. It is a default method that collects the stream items into an unmodifiable List.
  • The returned list is an implementation of Collections.unmodifiableList(new ArrayList<>(Arrays.asList(stream.toArray()))) where stream represents the underlying Stream of items.
  • The order of the items in the list will be same as the order in stream, if there is any.
  • As the returned List is unmodifiable; calls to any mutator method will always cause UnsupportedOperationException to be thrown.
  • It is a terminal operation.
Stream tokenStream = Stream.of("A", "B", "C", "D"); List tokenList = tokenStream.toList();
  • This method has been added in Java 10. It is a terminal operation that collects the stream items into an unmodifiable List.
  • The returned list is an instance of Collections.unmodifiableList() that is filled with stream items using JDK internal APIs able to access private methods of the JDK classes without using the reflection. In this case, the unmodifiable list is an implementation of SharedSecrets.getJavaUtilCollectionAccess().listFromTrustedArray(list.toArray()) where the list is an intermediate and mutable list of stream items.
  • The List does not allow the null values and the whole operation will throw the NullPointerException if there is a null value in the stream.
  • The order of items in the list is the same as the order of items in the stream, if there is any.
Stream tokenStream = Stream.of("A", "B", "C", "D"); List tokenList = tokenStream.collect(Collectors.toUnmodifiableList());
  • This method has been added in Java 8, along with the original Stream API. It is a terminal operation that collects the stream items into a mutable List.
  • The returned list is an instance of ArrayList class.
  • Similar to other versions, the order of the items in the mutable list will be same as the order in stream, if there is any.
Stream tokenStream = Stream.of("A", "B", "C", "D"); List tokenList = tokenStream.collect(Collectors.toList());

2. Collecting Stream into LinkedList

Use the Collectors.toCollection(LinkedList::new) API along with Stream.collect() API for collecting the Stream items into a LinkedList.

Stream tokenStream = Arrays.asList("A", "B", "C", "D").stream(); List tokenList = tokenStream .collect(Collectors.toCollection(LinkedList::new));

3. Filtering a Stream and Collect Items into List

Sometimes we need to find only specific items from the Stream and then add only those items to List. Here, we can use Stream.filter() method to pass a predicate that will return only those items which match the given pre-condition.

In the given example, we are filtering all employees whose salary is less than 400. Then we are collecting those employees into a List.

Stream employeeStream = Stream.of( new Employee(1, "A", 100), new Employee(2, "B", 200), new Employee(3, "C", 300), new Employee(4, "D", 400), new Employee(5, "E", 500), new Employee(6, "F", 600)); List employeeList = employeeStream .filter(e -> e.getSalary() < 400) .collect(Collectors.toList());

4. Collect Items from Infinite Stream into List

To convert an infinite stream into a list, we must limit the stream to a finite number of elements. Given example will work in the case of a stream of primitives.

IntStream infiniteNumberStream = IntStream.iterate(1, i -> i+1); List integerlist = infiniteNumberStream.limit(10) .boxed() .collect(Collectors.toList());

In this tutorial, we learned the different ways to work with streams and collect the stream items in a List.

As a general guideline, we can use Stream.toList() for unmodifiable lists, and use the Stream.collect(Collectors.toList()) for modifiable lists.

To collect items in any other List types, we must use the Stream.collect(Collectors.toCollection(LinkedList::new)) version of the solutions.

Источник

Читайте также:  Css align text vertically center
Оцените статью