Java Stream获取List中对象int属性最小值的排序方法
使用Java Stream获取List中对象int属性最小值并排序
想要利用Java Stream获取List中对象特定int属性的最小值并排序?按照以下步骤操作即可:
- 创建对象List: 首先,准备一个包含目标对象的List。2. 映射int属性: 使用
mapToInt()方法将对象的int类型属性a提取到int类型的流中。3. 排序: 使用sorted()方法对int流进行排序。4. 获取最小值: 使用min()方法获取排序后的最小值。
以下示例代码演示了具体操作:javaimport java.util.Arrays;import java.util.List;
class MyClass { private int a;
public MyClass(int a) { this.a = a; }
public int getA() { return a; }}
public class Main { public static void main(String[] args) { List
int min = myList.stream() .mapToInt(MyClass::getA) .sorted() .min() .orElse(0);
System.out.println('最小值: ' + min); }}
输出结果:
最小值: 1
原文地址: https://www.cveoy.top/t/topic/fhn6 著作权归作者所有。请勿转载和采集!