java 地图和 FindFirst

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38518313/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 03:28:00  来源:igfitidea点击:

Map and FindFirst

javajava-stream

提问by pppavan

Is it valid to use findFirst() and map() in pipeline.findFirst is shortcircuit method whereas map is intermediate operation.

在管道中使用 findFirst() 和 map() 是否有效。findFirst 是短路方法,而 map 是中间操作。

this.list.stream().filter(t -> t.name.equals("pavan")).findFirst().map(toUpperCase()).orElse(null);

Is it valid to use map in pipeline like above??

像上面那样在管道中使用地图是否有效?

回答by Ranjan

Yes, you canuse mapafter findFirst. The Key thing to know here is that findFirst() returns an Optionaland hence, you can't simply use the return value without first checking whether the optional has got a value or not. The snippet below assumes that you were working with a list of objects of Person class.

是的,您可以使用mapafter findFirst。这里要知道的关键是 findFirst() 返回一个Optional,因此,您不能简单地使用返回值而不先检查可选是否有值。下面的代码片段假设您正在使用 Person 类的对象列表。

Optional<String> result = this.list.stream()
    .filter(t -> t.name.equals("pavan")) // Returns a stream consisting of the elements of this stream that match the given predicate.
    .findFirst() // Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty. If the stream has no encounter order, then any element may be returned.
    .map(p -> p.name.toUpperCase()); // If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.

// This check is required!
if (result.isPresent()) {
    String name = result.get(); // If a value is present in this Optional, returns the value, otherwise throws NoSuchElementException.
    System.out.println(name);
} else {
    System.out.println("pavan not found!");
}

One more error with your snippet was where you were using toUpperCase. It needs a String, whereas the implicit argument that was getting passed in your snippet was an object of Person class.

您的代码片段的另一个错误是您使用toUpperCase. 它需要一个字符串,而在您的代码片段中传递的隐式参数是 Person 类的对象。