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
108 views
in Technique[技术] by (71.8m points)

java - How to get maximum value from of the first N values of an ArrayList?

There is an ArrayList which stores integer values. Suppose the arrayList stored values are: 10, 20, 30, 40, 50.

I know how to find the maximum value of the collection. I would have to do:

Collections.max(arrayList); 

But what should I do to find the maximum of the first 3 elements of the collection? So in this example, it would be 30. Is there a sublist function for collections?

question from:https://stackoverflow.com/questions/65926838/how-to-get-maximum-value-from-of-the-first-n-values-of-an-arraylist

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

1 Reply

0 votes
by (71.8m points)

List has a subList method that you can use:

Collections.max(arrayList.subList(0, 3))

There is no subList for Collections in general, as not all collections are lists and, for some, the "first N elements" doesn't make a lot of sense, as they don't maintain any meaningful order (e.g. HashSet).

You can take the first three elements of any Collection (in whatever order the collection will provide), by iterating through it with a limit. It's probably best to use a stream for this:

yourCollection.stream().limit(3).collect(Collectors.toList());

Or you can find what you're looking for directly on the stream, without collecting the elements in some collection:

Optional<Integer> max = yourCollection.stream.limit(3).max(Comparator.naturalOrder());

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

1.4m articles

1.4m replys

5 comments

57.0k users

...