How to make an object list from double values?

  • A+
Category:Languages

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?

 


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

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: