对List某元素求和方法

package com.atguli.common.utils.demo;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * User: ldj
 * Date: 2022/6/18
 * Time: 3:37
 * Description: No Description
 */
public class ListSumDemo {

    public static void main(String[] args) {
        List<Record> recordList = new ArrayList<>();
        recordList.add(new Record(1.5, 2.0));
        recordList.add(new Record(2.3, 3.0));
        recordList.add(new Record(4.5, 7.0));

        method1(recordList);
        method2(recordList);
    }

    private static void method1(List<Record> recordList) {
        Double totalRecordTime = 0.00;
        for (Record record : recordList) {
            Double recordEndTime = record.getRecordEndTime();
            Double recordStartTime = record.getRecordStartTime();

            if (Objects.nonNull(recordEndTime) && Objects.nonNull(recordStartTime)) {
                if (recordEndTime > recordStartTime) {
                    totalRecordTime += (recordEndTime - recordStartTime);
                }
            }
        }
        DecimalFormat decimalFormat = new DecimalFormat("#.00");
        System.out.println(decimalFormat.format(totalRecordTime));
    }

    private static void method2(List<Record> recordList) {
        Optional<Double> reduceStart = recordList.stream().map(Record::getRecordStartTime).reduce(Double::sum);
        Optional<Double> reduceEnd = recordList.stream().map(Record::getRecordEndTime).reduce(Double::sum);

        if (reduceStart.isPresent() && reduceEnd.isPresent()) {
            Double totalEndRecordTime = reduceEnd.get();
            Double totalStartRecordTime = reduceStart.get();

            if (totalEndRecordTime > totalStartRecordTime) {
                System.out.println("没做保留位数" + (reduceEnd.get() - reduceStart.get()));
                DecimalFormat decimalFormat = new DecimalFormat("#.00");
                System.out.println("保留2位数" + (decimalFormat.format(reduceEnd.get() - reduceStart.get())));
            }
        }
    }
}

@Data
@AllArgsConstructor
class Record {
    private Double recordStartTime;
    private Double recordEndTime;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值