0

I think it's easier to understand what i mean showing my code

        String[] words = text.split(" ");

        List<char[]> wordsInChars = new ArrayList<char[]>();
        for(String i: words){
            wordsInChars.add(i.toCharArray());
        }

so I create an array of Strings, taking the text variable as input, then i want to pass it to the List without going through that loop. Is it possible to skip the for loop altogether?

I've tried

List<char[]> wordsInChars = Arrays.asList(Arrays.stream(words).forEach(w -> w.toCharArray()));

Either way, which approach should be used? The code with the for loop works, but am not sure if just doing it all at declaration is just better.

edit: I actually managed with

List<char[]> wordsInChars = Arrays.stream(words).map(w -> w.toCharArray()).collect(Collectors.toList());

But feedback on which one of the two is better practice, is welcomed.

  • `Is it possible to skip the for loop altogether?` Nope. Even the stream equivalent still contains a loop, just one that's a little harder to see. – markspace Sep 05 '21 at 00:59
  • Also be careful as these are not equivalent. `Arrays.asList` does not return an `ArrayList` (in fact it return an immutable list). – markspace Sep 05 '21 at 01:00

2 Answers2

1

The quick answer is no. You are converting a string[] to a List and regardless of whether you will write the loop yourself or call some method that will do the loop for you, a loop is required to iterate over and convert these values. We can actually argue that multiple loops are necessary, as the String.toCharArray() method also iterates over each byte in the string in order to convert it to a char using the right encoding. That being said, there is nothing wrong with having a loop in your code. Unless your code is being called very very frequently, you won't even notice the difference in execution time.

Pieter12345
  • 1,713
  • 1
  • 11
  • 18
0

This is a different way, but it still has a loop internally so we haven't actually skipped the loop.

  String words = "This is some text I made.";
  List<char[]> s = Pattern.compile( "\\s+" ).splitAsStream( words ).map( String::toCharArray ).toList();
  for( char[] c : s ) 
     System.out.println( Arrays.toString( c ) );
markspace
  • 10,621
  • 3
  • 25
  • 39