How to count the number of custom objects in a list that have the same value for one of its attributes

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

class Item
{
     Integer id;
     BigDecimal itemNumber;
}

I have a list of items.

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

Now, what is best learned in java, the list Itemscontains Itemsthe same value for itemNumber.

+1
source share
4 answers

Search for a specific item with a certain position number :

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

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

To get item lists for all item numbers:

You can use HashMapfor 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 you can iterate over the key set and get all the elements for each key:

for (BigDecimal key : map.keySet()) {
    List<Item> listOfElementsWithSameKey = map.get(key);
}
+4

, , Item itemNumber

  • itemNumber?
  • , itemNumber?

, :

, , Java, :

BigInteger yourValue = // your desired value
List<Item> result = new ArrayList<Item>();
for (Item item : items) {
    if (item.itemNumber.equals(yourValue)) {
        item.add(item);
    }
}
+1

Override the equals method in the Element class , and in the call to the list of elements contains a method that calls the Item equal method.

 class Item
    {
         Integer id;
         BigDecimal itemNumber;

          public boolean equals(Item item) {
          if (this.itemNumber.equals(item.itemNumber)) {
            return true;
        }
    // getter and setter

}

In the Validation list

items.contains (item)

0
source

to count them:

List<Item> items = new ArrayList<>();
int count=0;
int idToFind=88;
for(Item i:items){
  if(i.getId()==idToFind)
    count++;
}

to get another list:

Item itemToFind;
List newList=list.contains(itemToFind);

and override the equal in your class to compare objects after the big decimal

-1
source

All Articles