使用Java中的流(Streams)获取用户输入值并对其进行处理。

huangapple go评论65阅读模式
英文:

Take user input values and process them using Streams in java

问题

以下代码可以找到用户输入中数字5的位置。是否有办法使用Java 8的流式操作(通过惰性求值)编写下面的代码,而且不需要在内存中存储数据。

import java.util.Scanner;
import java.util.stream.IntStream;

public class HelloWorld {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        
        long count = IntStream.iterate(1, i -> i + 1)
            .takeWhile(i -> s.hasNextInt() && s.nextInt() != 5)
            .count();
            
        System.out.println(count + 1); // Adding 1 to count for the position
    }
}
英文:

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);
        
     }
}

答案1

得分: 3

TL;DR: 在迭代方法优越的情况下,不要使用流。

虽然可以做到,但这种转换要么效率低下,要么非常棘手,无论如何都会违背流的目的。在你的代码中有两个地方,迭代方法在这里更胜一筹:

  • 你会改变状态变量 count,而流函数最好是无状态的

  • 你使用 break 来提前结束迭代,而流通常在所有元素处理完之前不会结束。

虽然可以在流中提前中断,但这很棘手。还可以通过将输入的每个标记与其序号配对来避免改变外部变量,但结果代码会变慢并且更难阅读。

以下是代码示例:

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

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);

huangapple
  • 本文由 发表于 2020年3月15日 15:00:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/60690486.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定