Java 8流中的arg max? [英] arg max in Java 8 streams?

查看:225
本文介绍了Java 8流中的arg max?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据产生double或int值的标准的最大化,我经常需要集合的最大元素。 Streams有max()函数,需要我实现一个比较器,我觉得很麻烦。是否有更简洁的语法,例如 names.stream()。argmax(String :: length)在以下示例中?

I often need the maximum element of a collection according to the maximization of a criterion which produces a double or int value. Streams have the max() function which requires me to implement a comparator, which I find cumbersome. Is there a more concise syntax, such as names.stream().argmax(String::length) in the following example?

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class ArgMax
{
    public static void main(String[] args)
    {
        List<String> names = Arrays.asList("John","Joe","Marilyn");
        String longestName = names.stream().max((String s,String t)->(Integer.compare(s.length(),t.length()))).get();
        System.out.println(longestName);
    }
}


推荐答案

使用

String longestName = names.stream().max(Comparator.comparing(String::length)).get();

来比较某些属性上的元素(可能比这更复杂,但不必) 。

to compare elements on some property (can be more complex than that, but doesn't have to).

正如Brian在评论中建议的那样,使用可选#get()这样做是不安全的,如果有可能为空。您更适合使用其中一种更安全的检索方法,例如 可选#orElse(对象) 如果没有最大值,它将为您提供一些默认值。

As Brian suggests in the comments, using Optional#get() like this is unsafe if there's a possibility that the Stream is empty. You'd be better suited to use one of the safer retrieval methods, such as Optional#orElse(Object) which will give you some default value if there is no max.

这篇关于Java 8流中的arg max?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆