Adam Jungen
Adam Jungen

Reputation: 437

How to make an object list from double values?

I have a list of doubles.

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

which has 20 double values. These values are average and sum values of Invoice objects.

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

//const, getters, setters
}

Thus it has a structure like that

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

How can I make a list of 10 invoice object from these average and sum values?

Upvotes: 0

Views: 557

Answers (4)

Oleksii Zghurskyi
Oleksii Zghurskyi

Reputation: 4365

Java 8 solution (without forming additional lists for avarages and sums):

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());

Upvotes: 2

Suyash Mittal
Suyash Mittal

Reputation: 73

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
}

Upvotes: 0

Darshan Mehta
Darshan Mehta

Reputation: 30809

You can do odd even filtering using streams, e.g.:

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());

Update

Once you have two lists, if you want Invoice object, you can stream over one list and construct the object, e.g.:

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

Update2

As @ernest_k suggested, this can also be done in a single iteration, e.g.:

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());

Upvotes: 7

Thilo
Thilo

Reputation: 262474

You can do

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)));
}

But how did this oddly shaped list come about in the first place?

Upvotes: 7

Related Questions