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?

2
  • @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. Commented Sep 26, 2018 at 4: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 stackoverflow.com/questions/1603170/… Commented Sep 26, 2018 at 5:57

1 Answer 1

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());
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.