Java - getting max value from an arraylist of objects?

后端 未结 5 958
北恋
北恋 2020-11-27 08:14

Is there an easy way to get the max value from one field of an object in an arraylist of objects?

For example, out of the following object, I was hoping to get the h

5条回答
  •  温柔的废话
    2020-11-27 08:28

    This has been answered multiple time already, but since it's the first result on google I will give a Java 8 answer with an example.

    Take a look at the stream feature. Then you can get the max form an List of Objects like this:

    List ourValues = new ArrayList<>();
    
    ourValues.stream().max(comparing(ValuePairs::getMValue)).get()
    

    By the way in your example, the attributes should be private. You can then access them with a getter.

提交回复
热议问题