java8 lamda string转list<Integer> string 转 int[] list求和

string 转 int[]

String orderIds = "1,5,8,7,123";
int[] orderArray = Arrays.stream(orderIds.split(","))
        .mapToInt(Integer::parseInt).toArray();
Arrays.stream(orderArray).forEach(System.out::println);

string转list <Integer>

List<Integer> listInt = Arrays.stream(orderIds.split(","))
                .mapToInt(Integer::parseInt).boxed().collect(Collectors.toList());
listInt.forEach(System.out::println);

list求和

list.stream().mapToDouble(User::getHeight).sum()//和
list.stream().mapToDouble(User::getHeight).max()//最大
list.stream().mapToDouble(User::getHeight).min()//最小
list.stream().mapToDouble(User::getHeight).average()//平均值

bigdecimal需要用到reduce求和。

public class HelloWorld {
    private static final DecimalFormat df = new DecimalFormat("0.00");//保留两位小数点
    public static void main(String[] args) {
        Random random = new Random();
        List<User> list = new ArrayList<>();
        for(int i=1;i<=5;i++) {
            double weight = random.nextDouble() * 100 + 100;//随机身高:100-200
            list.add(new User(i, new BigDecimal(weight).setScale(BigDecimal.ROUND_HALF_UP, 2)));
        }
        System.out.println("list:" + list);
        BigDecimal add = list.stream().map(User::getHeight).reduce(BigDecimal.ZERO, BigDecimal::add);
        System.out.println("身高 总和:" + df.format(add));
        Optional<User> max = list.stream().max((u1, u2) -> u1.getHeight().compareTo(u2.getHeight()));
        System.out.println("身高 最大:" + df.format(max.get().getHeight()));
        Optional<User> min = list.stream().min((u1, u2) -> u1.getHeight().compareTo(u2.getHeight()));
        System.out.println("身高 最小:" + df.format(min.get().getHeight()));
 
    }
    private static class User{
        Integer id;
        BigDecimal height;//身高
 
        public User(Integer id, BigDecimal height) {
            this.id = id;
            this.height = height;
        }
 
        public Integer getId() {
            return id;
        }
 
        public void setId(Integer id) {
            this.id = id;
        }
 
        public BigDecimal getHeight() {
            return height;
        }
 
        public void setHeight(BigDecimal height) {
            this.height = height;
        }
 
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", height=" + height +
                    '}';
        }
    }
 
}

摘自:java8 list统计(求和、最大、最小、平均)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值