Java Stream Collectors.toUnmodifiableList()

By Arvind Rai, October 02, 2020
On this page we will provide Java Stream Collectors.toUnmodifiableList() example introduced in Java 10. The Collectors.toUnmodifiableList() returns a Collector that accumulates the input elements into an unmodifiable List in encounter order. Find the method declaration from Java doc.
public static <T> Collector<T,?,List<T>> toUnmodifiableList() 
In unmodifiable List we cannot add or remove elements. Now let us discuss the examples to create unmodifiable List using Collectors.toUnmodifiableList() method.

Example-1

In this example we will create unmodifiable list of integer.
Example1.java
package com.concretepage;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class Example1 {
  public static void main(String[] args) {
	List<Integer> list1 = Stream.of(11, 20, 35)
		.collect(Collectors.toUnmodifiableList());
	System.out.println(list1);
	
	List<Integer> list2 = IntStream.range(10,  15).boxed()
		.collect(Collectors.toUnmodifiableList());
	System.out.println(list2);
	
	List<Integer> list3 = Arrays.asList(2, 3, 4).stream().map(i -> i * 2)
		.collect(Collectors.toUnmodifiableList());
	System.out.println(list3);	
  }
} 
Output
[11, 20, 35]
[10, 11, 12, 13, 14]
[4, 6, 8] 
When we try to modify unmodifiable list as given below,
list1.add(40); 
Exception will be thrown.
Exception in thread "main" java.lang.UnsupportedOperationException 

Example-2

In this example we will create unmodifiable list of string.
Example2.java
package com.concretepage;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Example2 {
  public static void main(String[] args) {
	List<String> list1 = Stream.of("Mahesh", "Krishn", "Ram")
		.collect(Collectors.toUnmodifiableList());
	System.out.println(list1);
	
	List<String> list2 = Stream.of("Mahesh", "Krishn", "Ram").map(s -> "Sri " + s)
		.collect(Collectors.toUnmodifiableList());
	System.out.println(list2);	
	
  }
} 
Output
[Mahesh, Krishn, Ram]
[Sri Mahesh, Sri Krishn, Sri Ram] 

Example 3

In this example we will create unmodifiable list of objects.
Example3.java
package com.concretepage;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Example3 {
  public static void main(String[] args) {
     List<User> list = Stream.of(new User(1, "Ram"), new User(2, "Shyam"))
        .collect(Collectors.toUnmodifiableList());
     System.out.println(list);
  }
}
class User {
	private int id;
	private String name;
	public User(int id, String name) {
	  this.id = id;
	  this.name = name;
	}
        //Sets and Gets

	@Override
	public String toString() {
	  return id + "-" + name;
	}
} 
Output
[1-Ram, 2-Shyam] 

Reference

Collectors.toUnmodifiableList
POSTED BY
ARVIND RAI
ARVIND RAI







©2024 concretepage.com | Privacy Policy | Contact Us