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;
}
对List某元素求和方法
最新推荐文章于 2023-12-04 14:11:11 发布