Teguh Teguh - 1 year ago 94
Java Question

How to combine list object java?

I have two list object, I want combine them, this is my class

public class DailyIncome {

private String date;
private String total;


and I have two list, this is list A

enter image description here

and this is list B

enter image description here

and my expectation result like this

enter image description here

is possible to realize my expectation?

Answer Source

"is possible to realize my expectation?"

Yes, it is. But you'd better write down what you have tried so far before you ask a question in SO.

1, Your DailyIncome doesn't have Getter and Setter and the field is decorated with private. How would you expect it to be visited from other class?

2, For your scenario, I think Map should be used.

Please try the code below for your reference.

public class DailyIncome {
     public String date;
     public String total;

     public DailyIncome(String date, String total){
         this.date = date;
         this.total = total;

And also the Test class.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class Test {
    private List<DailyIncome> shopA = new ArrayList<DailyIncome>();
    private List<DailyIncome> shopB = new ArrayList<DailyIncome>();
    private List<List<String>> shop = new ArrayList<List<String>>();
    public void initialize(){
        shopA.add(new DailyIncome("20-08-16", "4"));
        shopA.add(new DailyIncome("21-08-16", "8"));
        shopA.add(new DailyIncome("23-08-16", "3"));

        shopB.add(new DailyIncome("20-08-16", "6"));
        shopB.add(new DailyIncome("21-08-16", "7"));
        shopB.add(new DailyIncome("22-08-16", "8"));
    public void calculate(){

        Map<String, String> mapA = new HashMap<String, String>();
        Map<String, String> mapB = new HashMap<String, String>();

        for(DailyIncome income: shopA){
            mapA.put(income.date, income.total);

        for(DailyIncome income: shopB){
            mapB.put(income.date, income.total);

        Set<String> keySet = new HashSet<String>();

        Object keyArr[] = keySet.toArray();

        for(int i = 0; i < keyArr.length; i++){
            String key = (String)keyArr[i];
            String totalA = mapA.containsKey(key) ? mapA.get(key):"0";
            String totalB = mapB.containsKey(key) ? mapB.get(key):"0";
            List<String> itemList = new ArrayList<String>();

         * print
        for(List<String> itemList: shop){
            System.out.print(itemList.get(0) + "   ");
            System.out.print(itemList.get(1) + "   ");

    public static void main(String args[]){
        Test obj = new Test();