Open In App

Program to convert List of String to List of Integer in Java

The Java.util.List is a child interface of Collection. It is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. List Interface is implemented by ArrayList, LinkedList, Vector, and Stack classes.

1. Using Java 8 Stream API:

A Stream is a sequence of objects that supports various methods that can be pipelined to produce the desired result. Java 8 Stream API can be used to convert List to List.



Algorithm:

Program:






// Java Program to convert
// List<String> to List<Integer> in Java 8
import java.util.*;
import java.util.stream.*;
  
class GFG {
    public static void main(String args[]) {
  
        // Create a list of String
        List<String> listOfString = Arrays.asList("1", "2", "3", "4", "5");
  
        // Print the list of String
        System.out.println("List of String: " + listOfString);
  
        // Convert List of String to List of Integer
        List<Integer> listOfInteger = listOfString.stream()
                            .map(Integer::valueOf)
                            .collect(Collectors.toList());      
  
        // Print the list of Integer
        System.out.println("List of Integer: " + listOfInteger);
    }
}

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<String> to List<Integer> in Java 8
// Using Guava's List.transform()
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
  
class GFG {
  
    // Generic function to convert List of
    // String to List of Integer
    public static List<Integer> convertStringListToIntList(List<String> listOfString,
                                                           Function<String, Integer> function) {
        return listOfString.stream()
                .map(function)
                .collect(Collectors.toList());
    }
  
    public static void main(String args[]) {
  
        // Create a list of String
        List<String> listOfString = Arrays.asList("1", "2", "3", "4", "5");
  
        // Print the list of String
        System.out.println("List of String: " + listOfString);
  
        // Convert List of String to list of Integer
        List<Integer> listOfInteger = convertStringListToIntList(listOfString, Integer::parseInt);
  
        // Print the list of Integer
        System.out.println("List of Integer: " + listOfInteger);
    }
}

Output
List of String: [1, 2, 3, 4, 5]
List of Integer: [1, 2, 3, 4, 5]


Article Tags :