Take user input values and process them using Streams in java

pavan :

Below code finds the position of a number 5 in the user inputs given. Is there a way I can write the below code using java 8 Streams through lazy evaluation and without storing the data in memory.

public class HelloWorld{

     public static void main(String []args){
        Scanner s=new Scanner(System.in);
        int count=0;

        while(s.hasNextInt()){
            count++;
            if(s.nextInt()==5){
                break;
            }
        }
        System.out.println(count);

     }
}
Alex :

TL;DR: Don't use streams where iterative approach is superior.

While it can be done, such transformation would be either inefficient or quite tricky, and in any case would defeat the purpose of the stream. There are two spots in your code, which makes the iterative approach here preferable to streaming:

  • you mutate a state variable count, while stream functions should be preferably stateless

  • you use break in order to finish the iteration prematurely, while streams normally do not finish until all the elements are processed.

It is possible to break from streams prematurely, but it's tricky. It's also possible to avoid mutating an external variable by pairing each token of the input with its sequence number, but the resulting code will be slower and harder to read.

An example of how the code could look like:

System.out.println(new BufferedReader(new InputStreamReader(System.in)).lines()
    .mapToInt(Integer::valueOf)
    .takeWhile(number -> number != 5)
    .count() + 1);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=276546&siteId=1