登录
首页 >  文章 >  java教程

java8的stream怎么取max

来源:亿速云

时间:2024-04-06 15:39:30 351浏览 收藏

目前golang学习网上已经有很多关于文章的文章了,自己在初次阅读这些文章中,也见识到了很多学习思路;那么本文《java8的stream怎么取max》,也希望能帮助到大家,如果阅读完后真的对你学习文章有帮助,欢迎动动手指,评论留言并分享~

java8的stream取max

 public static void main(String[] args) {
        List 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();

java8 stream详解~聚合(max/min/count)

maxmincount这些字眼你一定不陌生,没错,在mysql中我们常用它们进行数据统计。

Java stream中也引入了这些概念和用法,极大地方便了我们对集合、数组的数据统计工作。

java8的stream怎么取max

「案例一:获取String集合中最长的元素。」

public class StreamTest {
 public static void main(String[] args) {
  List list = Arrays.asList("adnm", "admmt", "pot", "xbangd", "weoujgsd");
 
  Optional max = list.stream().max(Comparator.comparing(String::length));
  System.out.println("最长的字符串:" + max.get());
 }
}

「案例二:获取Integer集合中的最大值。」

public class StreamTest {
 public static void main(String[] args) {
  List list = Arrays.asList(7, 6, 9, 4, 11, 6);
 
  // 自然排序
  Optional max = list.stream().max(Integer::compareTo);
  // 自定义排序
  Optional max2 = list.stream().max(new Comparator() {
   @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 personList = new ArrayList();
  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 max = personList.stream().max(Comparator.comparingInt(Person::getSalary));
  System.out.println("员工工资最大值:" + max.get().getSalary());
 }
}

「案例四:计算Integer集合中大于6的元素的个数。」

import java.util.Arrays;
import java.util.List;
 
public class StreamTest {
 public static void main(String[] args) {
  List 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》的内容介绍就到此结束,如果有什么疑问或者建议,可以在golang学习网公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!

声明:本文转载于:亿速云 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>