简体   繁体   中英

what would be best way to convert List of ArrayList<Object> to a custom object java11 Spring boot 2.1

I have List of ArrayList of Objects where objects could be text,BigDecimal, Long

List<Object> data = {
{"date","prize1","cardsNumers","cardObtained","totalCards","anotherPrize"},
{"2020-05-01",435345.67,43,56,67,345345345},
{"2020-03-01",45656.2,34,67,23,456456},
{"2020-02-01",56565,34,56,67,878987}
}

1st, 2nd,3rd and so on objects in arrayList are the values for each filed mentioned in the 0th arraylist. in table representation as below,

在此处输入图像描述

I would like to take sum of each filed from above and assign to the same field of the below custom Object,

public class SumObject {

private Date date;
private BigDecimal sumPrize1;
private BigDecimal sumCardsNumers;
private long sumCardObtained;
private long sumTotalCards;
private long sumAnotherPrize;
}

I achieved this by traversing arrayList in the List,and obtained value by get(index) method. But I would like to know if there is any other good way this can be done.

If anyone has any suggestion, kindly post the answer or give me the direction of a document which I can read through.

Thanks in advance.

In this case, it's better to use the following data structure to describe a table data:

List<BigDecimal> prizes1 = {435345.67, 45656.2, 56565};
List<BigDecimal> cardsNumbers = {43, 34, 34};
List<Long> cardsObtained = {56, 67, 56};
List<Long> totalCards = {67, 23, 67};
List<Long> anotherPrizes = {345345345, 456456, 878987};

In this way every table row is described by the get(index) on every List. This parallel lists are useful for your aggregation:

BigDecimal sumPrize1 = prizes1.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
BigDecimal sumCardsNumers = cardsNumebrs.stream().reduce(BigDecimal.ZERO, BigDecimal::add);
long sumCardObtained = cardsObtained.stream().sum();
long sumTotalCards = totalCards.stream().sum();
long sumAnotherPrize = anotherPrizes.stream().sum();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM