Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

arg max in Java 8 streams?

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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...