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?
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());
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments