Java.util.List is a sub-interface of Collection. It is an ordered collection of objects in which repeated values ??can be stored. Since List retains the insertion order, it allows positional access and insertion of items. The List interface is implemented by the ArrayList, LinkedList, Vector, and Stack classes.
1.Using Java 8 Stream API: A sequence is a sequence of objects that supports multiple methods that can be piped to produce the desired result. The Java 8 Sequence API can be used to convert lists to lists.
Algorithm:
Program:
// Java Program to convert // List to List in Java 8 import java.util.*; import java.util.stream.*; import java.util.function.*; class GFG { // Generic function to convert List of // String to List of String public static <T, U> List convertIntListToStringList(List listOfInteger, Function<T, U> function) { return listOfInteger.stream() .map(function) .collect(Collectors.toList()); } public static void main(String args[]) { // Create a List of Integer List listOfInteger = Arrays.asList(1, 2, 3, 4, 5); // Print the List of Integer System.out.println("List of Integer: " + listOfInteger); // Convert List of Integer to List of String List listOfString = convertIntListToStringList( listOfInteger, s -> String.valueOf(s)); // Print the List of String System.out.println("List of String: " + listOfString); } }
Output:
List of String: [1, 2, 3, 4, 5] List of Integer: [1, 2, 3, 4, 5]
2. Using Guava’s List.transform():
Algorithm:
Program:
// Java Program to convert // List to List in Java 8 import com.google.common.base.Function; import com.google.common.collect.Lists; import java.util.*; import java.util.stream.*; class GFG { // Generic function to convert List of // String to List of String public static <T, U> List convertIntListToStringList(List listOfInteger, Function<T, U> function) { return Lists.transform(listOfInteger, function); } public static void main(String args[]) { // Create a List of Integer List listOfInteger = Arrays.asList(1, 2, 3, 4, 5); // Print the List of Integer System.out.println("List of Integer: " + listOfInteger); // Convert List of Integer to List of String List listOfString = convertIntListToStringList( listOfInteger, s -> String.valueOf(s)); // Print the List of String System.out.println("List of String: " + listOfString); } }
Output:
List of String: [1, 2, 3, 4, 5] List of Integer: [1, 2, 3, 4, 5]
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.