2

This is not a duplicate question because I'm specifically asking to convert an ARRAY of STRINGS to a LIST of INTEGERS. In other words, converting both different types of lists AND different object types at the same time.

import java.util.*;
import java.util.stream.Collectors;

String[] allAnswers = {"2", "4", "1"}

int[] allAnswersInts = Arrays.stream(allAnswers).mapToInt(Integer::parseInt).toArray();

List<Integer> allAnswerList = Arrays.stream(allAnswersInts).boxed().collect(Collectors.toList());

Is there a faster or more practical way to do this?

William Toscano
  • 209
  • 2
  • 10
  • @napadhyaya This is not a duplicate question because I'm specifically asking to convert an ARRAY of STRINGS to a LIST of INTEGERS. In other words, converting both different types of lists AND different object types at the same time. – William Toscano Sep 26 '18 at 04:30
  • Though this question has already been answered and closed, there is a very simple (if not particularly performant) solution to that issue: linq provides useful extension methods like `ToArray` and `ToList`. See https://stackoverflow.com/questions/1603170/conversion-of-system-array-to-list – Rook Sep 26 '18 at 05:57

1 Answers1

3

You only need to stream once.

Instead of using int Integer::parseInt(String s), you should use Integer Integer::valueOf(String s), so you don't have to call boxed() or rely on auto-boxing.

Then use collect(Collectors.toList()) directly, instead of creating intermediate array first.

List<Integer> allAnswerList = Arrays.stream(allAnswers)    // stream of String
                                    .map(Integer::valueOf) // stream of Integer
                                    .collect(Collectors.toList());
Andreas
  • 154,647
  • 11
  • 152
  • 247