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?.

1
  • 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 Commented Oct 25, 2019 at 12:48

1 Answer 1

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

2 Comments

why not just inline the variable and return directly.
@Naman Thank you for pointing that out. I've just copy pasted OPs code.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.