Home > Software engineering >  How to do add and subtract elements from particular object in list using java?
How to do add and subtract elements from particular object in list using java?

Time:12-10

I have list of Objects in a list something like this , now my requirement here is to add all the qty object having same id and subtract approved qty from the entire qty , approved qty value is never changed

[
  {
    "qty": 50,
    "remainingQty": 0,
    "ids": "123456",
    "approvedQty": 600
  },
  {
    "qty": 60,
    "remainingQty": 0,
    "ids": "123456",
    "approvedQty": 600
  },
  {
    "qty": 100,
    "remainingQty": 0,
    "ids": "12345",
    "approvedQty": 345
  }
]


Expected Output is something like this 

[
  {
    "qty": 110,
    "remainingQty": 490,
    "ids": "123456",
    "approvedQty": 600
  },
  {
    "qty": 100,
    "remainingQty": 245,
    "ids": "12345",
    "approvedQty": 345
  }
]

I was trying something like this ,

  Map<String, List<Items>> elementsByItemId = initialItemList.stream()
                .collect(Collectors.groupingBy(Items::getIds));

        initialItemList = elementsByItemId.entrySet().stream()
                .map(entry -> new SaLineItems(entry.getValue().stream().collect(Collectors.summingDouble(Items::getQty)),

                        entry.getKey()))
                .collect(Collectors.toList());

any sort of help is appreciated ..

CodePudding user response:

The following should work as expected:

public class Main {
    public static void main(String[] args) {
        List<Items> initialItemList = new ArrayList<>();
        initialItemList.add(new Items(50, 0, "123456", 600));
        initialItemList.add(new Items(60, 0, "123456", 600));
        initialItemList.add(new Items(100, 0, "12345", 345));

        Map<String, List<Items>> elementsByItemId = initialItemList.stream()
                .collect(Collectors.groupingBy(Items::getIds));

        List<Items> processedItems = elementsByItemId.values().stream().map(items -> {
            String ids = "";
            int qty = 0;
            int approvedQty = 0;
            for (Items item : items) {
                ids = item.getIds();
                approvedQty = item.getApprovedQty();
                qty  = item.getQty();
            }

            return new Items(qty, approvedQty - qty, ids, approvedQty);
        }).collect(Collectors.toList());
        System.out.println(processedItems);
    }
}
  • Related