String List to Integer List Conversion Using Java Streams | Java 8 Stream

 Java 8 Programs

Convert String List to Integer List


 




 package org.practice.basicprgms;


import java.util.Arrays;

import java.util.List;

import java.util.stream.Collectors;


public class ConvertLlistOfStringIntoListOfInteger {


public static void main(String[] args) {

List<String> strList = Arrays.asList("10","15","2h5","30","66","abc","-12");

// Method 1: Using parseInt and Collect method.

List<Integer> numList1 =

strList.stream()

.filter(num -> num.matches("\\d+"))

.map(num -> Integer.parseInt(num))

.collect(Collectors.toList());

System.out.println("Integer List :" + numList1);

System.out.println("===============================================");

// Method 2: Using toArray() Method

int[] numArray =

strList.stream()

.filter(num -> num.matches("\\d+"))

.mapToInt(num -> Integer.parseInt(num))

.toArray();

System.out.println("Integer Array : "+ Arrays.toString(numArray));

System.out.println("===============================================");

// Method 3 : Using toList() method

List<Integer> numList3 =

strList.stream()

.filter(num -> num.matches("\\d+"))

.map(Integer::parseInt)

.toList();

System.out.println("Using toList() Method "+ numList3);

// Method 4 : Using collect and method reference

System.out.println("===============================================");

List<Integer> numList4 =

strList.stream()

.filter(num -> num.matches("\\d+"))

.map(Integer::parseInt)

.collect(Collectors.toList());

System.out.println("Using method refer and Collect " + numList4);

}


}


Post a Comment

0 Comments