0

I have a method which takes input via a scanner, formats with toUpperCase and splits on whitespace. It also takes an input limit. So only the first N words will appear in the outputted array.

public String[] getMultiLineInput(int inputLimit) 

        String[] input = Arrays.stream(scanner.nextLine().toUpperCase().split("\\s+"))
                .limit(inputLimit)
                .toArray(size -> new String[inputLimit]);

        return input;
    }

My method works as intended however I would now like to add an additional condition. That if the String retrieved by scanner.nextline() is smaller than the input limit. Then it will trim it even further to avoid NULL entries in my String[]

public String[] getMultiLineInput(int inputLimit){

        System.out.println("> ");
        String[] input = Arrays.stream(scanner.nextLine().toUpperCase().split("\\s+"))
                .limit(inputLimit)
                .toArray(size -> new String[inputLimit]);

        ArrayList<String> temp = new ArrayList<>();

        for ( String word : input){
            if ( word != null){
                temp.add(word);
            }
        }

        String [] trimmedarray = temp.toArray(new String[temp.size()]);
        return trimmedarray;

    }

Is there a more concise/efficient way of doing this with streams + lamda (new to java 8)?. Is there a way of this additional step being included into my stream?.

Naman
  • 27,789
  • 26
  • 218
  • 353
  • What do you mean by *.. if the String retrieved by scanner.nextline() is smaller than the input limit.*? You do removing null without any condition in the above code – Thiyagu Oct 25 '19 at 12:48

1 Answers1

1

When calling to array don't specify the length yourself. Use method reference instead which makes your code even more readable:

public String[] getMultiLineInput(int inputLimit) {
    String[] input = Arrays.stream(scanner.nextLine().toUpperCase().split("\\s+"))
            .limit(inputLimit)
            .toArray(String[]::new);
    return input;
}

Or as @Naman suggested:

public String[] getMultiLineInput(int inputLimit) {
    return Arrays.stream(scanner.nextLine().toUpperCase().split("\\s+"))
                 .limit(inputLimit)
                 .toArray(String[]::new);
}
Eritrean
  • 15,851
  • 3
  • 22
  • 28