简体   繁体   中英

sum by group inside a looping of list object in java

i've been stuck for creating a subtotal from the list object i have. The Code like this,

private List<Object> getData() {
    List<Object> items = new ArrayList<>();
    List<Object> objectList = dataBaseHelper.fetchData();

 for (Object obj : objectList) {
    items.add(new Object(obj.one, obj.two));
 }

return items;

}

i can make the list just fine, like

a 1
a 2
a 3
b 1
b 2
b 3

but i want to make my list like this,

    a       1
    a       2
    a       3
subTotal a  6

    b       1
    b       2
    b       3
subTotal b  6

can some one guide how i can make that?

Thanks before,

Alright, I'll try to answer in a somewhat abstract way.

First to make things less ambiguous, let's assume that dataBaseHelper.fetchData() returns a List<MyObject> where MyObject has the following members:

  • public String name;
  • public int price;

Now let's assume we want to calculate the subtotal grouping by name. We then need a data structure that can hold data like this. Some simplicity sake, let's just use a Map of Lists:

Map<String, List<MyObject>> subTotalsByName = new HashMap<>();

Then we can loop through the returned data:

private Map<String, List<MyObject>> getData() {
  Map<String, List<MyObject>> subTotalsByName = new HashMap<>();
  List<MyObject> objectList = dataBaseHelper.fetchData();

  for (MyObject obj : objectList) {
    List<MyObject> subTotalList = subTotalsByName.get(obj.name);
    if (subTotalList == null){
        subTotalList = new ArrayList<>();
        subTotalsByName.put(obj.name, subTotalList);
    }

    subTotalList.add(obj);
  }

  return subTotalsByName;
}

(Note: the above code is untested, treat it as pseudo-code, just to give you an idea of grouping by sub-totals)

Now you have a Map of List of MyObject s, now you just have to iterate through the map of calculate the subtotals! (In fact, this may be done earlier in the above loop, but to make things clearer, we waste a bit more CPU cycles to explicitly do stuff. It's also a good idea not to do premature optimizations :) )

for (Entry<String, List<MyObject>> entry : subTotalsByName.entrySet()) {

  int subtotal = 0;

  List<MyObject> myObjects = entry.getValue();
  for (MyObject myObj : myObjects){
    System.out.println(myObj.name + " " + myObj.price);
    subtotal += myObj.price;
  }

  System.out.println("subTotal for " + entry.getKey() + " is " + subtotal);
  System.out.println();
}

(Again, this is untested, treat as pseudo-code)

Then you get outputs like this:

a 1
a 2
a 3
subTotal for a is 6

b 4
b 5
b 6
subTotal for b is 15

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