Search code examples
javaobjectcastinginteger

How to convert a list of object to a list of integer in Java?


I have a inner list of object into a list and I want to convert it in a list of Integer, because I know that its elements are Integer.

List<List<Object>> valuesModel = FCSMs.get(0).getValues();
            for (List<Object> innerList : valuesModel) {

//CONVERT LIST OF OBJECT TO LIST OF INTEGER

}

How Can I do?


Solution

  • You can do it like this. Since you know that all objects are Integers, no checks are done to avoid ClassCastExceptions.

    • Stream the list of lists to a stream of lists.
    • Then flatten those lists into a stream of object.
    • cast the object to an Integer.
    • and collect into a List
    List<List<Object>> valuesModel = List.of(List.of(1,2,3,4), List.of(5,6,7,8));
    
    List<Integer> integers = valuesModel.stream()
               .flatMap(Collection::stream)
                .map(ob->(Integer)ob)
                 .collect(Collectors.toList());
    
    System.out.println(integers);
    

    Prints

    [1, 2, 3, 4, 5, 6, 7, 8]