0

I have a String array of numbers that I read in from a data file using a Scanner:

6 10 13 14 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185

I take a line from the file and convert it into a String array. Is there a simple way to convert the String array into an int array without a for loop?

String indices = input.nextLine();
String[] clean = indices.split("\\s+");
4
  • Why do you need to avoid a loop, is this an assignment of some sort? Are utility functions allowed or are you after a recursive solution? Commented Jul 30, 2018 at 19:01
  • I don't need to avoid it, I just thought there might be some sort of method to this in less lines. Commented Jul 30, 2018 at 19:02
  • Similar, but I'm specifically looking for ways without a loop. Commented Jul 30, 2018 at 21:07
  • That question has answers that avoid loops (or at least: the loops are hidden from you, because believe me: loops will be used internally) Commented Jul 31, 2018 at 15:05

1 Answer 1

2

Without a forloop may involve Streams and mapping :

String indices = input.nextLine();
int[] array = Arrays.stream(indices.split("\\s+")).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(array));
// [6, 10, 13, 14, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185]
Sign up to request clarification or add additional context in comments.

2 Comments

Technically, that involves a loop under-the-hood, right?
Nevermind, looks like this is what OP was asking for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.