How to use Java 8 Stream in an Object[] list

Asked

Viewed 403 times

3

Imagine the following scenario: A list of Object[]. Something like that:

    List<Object[]> lista = new ArrayList<>();
    Object[] dados = new Object[3];
    dados[0] = 1;
    dados[1] = 20;
    dados[1] = "cristiano";
    lista.add(dados);

    dados = new Object[3]; 
    dados[0] = 2;
    dados[1] = 40;
    dados[1] = "fulano";
    lista.add(dados);

How would I return a list of integers, containing only the values of the first position of the array, using the Stream java 8?

The expected result would be as follows:

1
2

1 answer

6


Use this:

List<Integer> lista2 = lista.stream()
        .map(x -> (Integer) x[0])
        .collect(Collectors.toList());

System.out.println(lista2);

Exit:

[1, 2]

See here working on ideone.

  • Man, that’s right. Thank you so much!

  • 1

    @Cristianobombazar If you have no further doubt about this question, click on what appears below the voting number of this answer (or the other if you prefer) to mark it as accepted and mark your question as resolved. If you still have any questions, feel free to comment. It was a pleasure to help you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.