如何从双精度值制成对象列表?

时间:2019-02-08 09:42:01

标签: java

我有一个双打列表。

List<Double> averagesAndSums = new ArrayList<>();

,具有20个double值。这些值是发票对象的平均值和总和值。

public class Invoice {
    private double average;
    private double sum;

//const, getters, setters
}

因此它具有这样的结构

index 0 = average, index 1 = sum, index 2= average, index 3 = sum, 
index 4 = average, index 5 = sum ... so on.

如何从这些平均值和总和中列出10个发票对象?

4 个答案:

答案 0 :(得分:7)

您可以使用流进行奇偶过滤,例如:

List<Double> list = Arrays.asList(1d, 5d, 3d, 6d);

List<Double> averages = IntStream.range(0, list.size())
        .filter(i -> (i % 2 == 0))
        .mapToObj(i -> list.get(i))
        .collect(Collectors.toList());

List<Double> sums = IntStream.range(0, list.size())
        .filter(i -> (i % 2 != 0))
        .mapToObj(i -> list.get(i))
        .collect(Collectors.toList());

更新

一旦有两个列表,如果要使用Invoice对象,则可以流式处理一个列表并构造该对象,例如:

List<Invoice> invoices = IntStream.range(0, sums.size())
    .mapToObj(i -> new Invoice(averages.get(i), sums.get(i)))
    .collect(Collectors.toList());

Update2

正如@ernest_k所建议的,这也可以在单个迭代中完成,例如:

List<Invoice> invoices2 = IntStream.range(0, list.size())
    .filter(i -> (i % 2 == 0))
    .mapToObj(i -> new Invoice(list.get(i), list.get(i + 1)))
    .collect(Collectors.toList());

答案 1 :(得分:7)

你可以

List<Invoice> result = new ArrayList<>(averageAndSums.size() / 2);
for (int i = 0; i < averageAndSums.size(); i += 2){
    result.add(new Invoice(averageAndSums.get(i), averageAndSums.get(i + 1)));
}

但是这个奇怪形状的列表是如何首先出现的?

答案 2 :(得分:2)

Java 8解决方案(不构成avaragessums的其他列表):

List<Invoice> invoices = 
   IntStream.iterate(0, i -> i + 2)
            .limit(averageAndSums.size() / 2)
            .mapToObj(i -> new Invoice(averageAndSums.get(i), averageAndSums.get(i + 1)))
            .collect(Collectors.toList());

答案 3 :(得分:0)

List<Invoice> invoiceList = new ArrayList<>(averageAndSums.size()/2);
for(int i = 0; i < averageAndSums.size(); i +=2 ) {
    Double avg = averageAndSums[i];
    Double sum = averageAndSums[i+1];
    invoiceList.add(new Invoice(avg, sum)); //Considering the Invoice class has the required constructor
}