public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6); Integer max = list.stream().max((a, b) -> { if (a > b) { return 1; } else return -1; }).get(); System.out.println(max); }
注意點:這裡判斷大小是透過正負數和0值。而不是直接寫成
if (a > b) { return a; } else return b;
可以簡化寫法
int max = list.stream().max((a, b) -> a > b ? 1 : -1).get();
max
、 min
、count
這些字眼你一定不陌生,沒錯,在mysql中我們常用它們進行資料統計。
Java stream中也引入了這些概念和用法,大大方便了我們對集合、陣列的資料統計工作。
public class StreamTest { public static void main(String[] args) { List<String> list = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd"); Optional<String> max = list.stream().max(Comparator.comparing(String::length)); System.out.println("最长的字符串:" + max.get()); } }
public class StreamTest { public static void main(String[] args) { List<Integer> list = Arrays.asList(7, 6, 9, 4, 11, 6); // 自然排序 Optional<Integer> max = list.stream().max(Integer::compareTo); // 自定义排序 Optional<Integer> max2 = list.stream().max(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } }); System.out.println("自然排序的最大值:" + max.get()); System.out.println("自定义排序的最大值:" + max2.get()); } }
public class StreamTest { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 23, "male", "New York")); personList.add(new Person("Jack", 7000, 25, "male", "Washington")); personList.add(new Person("Lily", 7800, 21, "female", "Washington")); personList.add(new Person("Anni", 8200, 24, "female", "New York")); personList.add(new Person("Owen", 9500, 25, "male", "New York")); personList.add(new Person("Alisa", 7900, 26, "female", "New York")); Optional<Person> max = personList.stream().max(Comparator.comparingInt(Person::getSalary)); System.out.println("员工工资最大值:" + max.get().getSalary()); } }
import java.util.Arrays; import java.util.List; public class StreamTest { public static void main(String[] args) { List<Integer> list = Arrays.asList(7, 6, 4, 8, 2, 11, 9); long count = list.stream().filter(x -> x > 6).count(); System.out.println("list中大于6的元素个数:" + count); } }
以上是java8的stream怎麼取max的詳細內容。更多資訊請關注PHP中文網其他相關文章!