您好,登錄后才能下訂單哦!
這篇文章主要講解了“java8的stream怎么取max”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“java8的stream怎么取max”吧!
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); }
注意點(diǎn):這里判斷大小是通過正負(fù)數(shù)和0值。 而不是直接寫成
if (a > b) { return a; } else return b;
可以簡(jiǎn)化寫法
int max = list.stream().max((a, b) -> a > b ? 1 : -1).get();
max
、min
、count
這些字眼你一定不陌生,沒錯(cuò),在mysql中我們常用它們進(jìn)行數(shù)據(jù)統(tǒng)計(jì)。
Java stream中也引入了這些概念和用法,極大地方便了我們對(duì)集合、數(shù)組的數(shù)據(jù)統(tǒng)計(jì)工作。
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("最長(zhǎng)的字符串:" + 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的元素個(gè)數(shù):" + count); } }
感謝各位的閱讀,以上就是“java8的stream怎么取max”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)java8的stream怎么取max這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。