Skip to content
Advertisement

How to count number of custom objects in list which have same value for one of its attribute

I am programming in java. Say I have an custom object Item

class Item
{
     Integer id;
     BigDecimal itemNumber;
}

I have list of Items.

List<Item> items = new ArrayList<>();

Now, What is best way in java to know, list of Items contain some Items with same value for itemNumber.

Advertisement

Answer

To search for a specific item with some item number:

//result list
List<Item> itemsWithSameNumber = new ArrayList<>();

for (Item item : items) {
    if (item.getItemNumber().equals(yourKey)) {
        itemsWithSameNumber.add(item);
    }
}

To get lists of items for all item numbers:

You can use a HashMap for this case:

//result map
HashMap<BigDecimal, List<Item>> map = new HashMap<>();

for (Item item : items) {
    List<Item> itemsWithSameNumber = map.get(item.getItemNumber());
    if (itemsWithSameNumber == null) { //does not exist in map yet
        itemsWithSameNumber = new ArrayList<Item>();
        map.put(item.getItemNumber(), itemsWithSameNumber);
    }
    itemsWithSameNumber.add(item); //now add the item to the list for this key
}

Later on, you can iterate over map’s keyset and get all items for each key:

for (BigDecimal key : map.keySet()) {
    List<Item> listOfElementsWithSameKey = map.get(key);
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement