简体   繁体   中英

How to count number of times an item is in a list

I have made a collection of items. For example:

  • Bread
  • Cheese
  • Coke
  • Coke
  • Cheese
  • Crisps

I want it to print out a condensed version of the list. Expected result:

  • 1 x Bread
  • 2 x Cheese
  • 2 x Coke
  • 1 x Crisps

I have been approaching it with a for loop nested within a for loop. But I can't seem to quite get it to work.

The item class holds two variables; name and price of item.

I have been successful in getting loops to count the total, output the total value and output each item as a string. But I just can't quite get it to do this.

I have tried writing the following pseudo code to help me but I'm still stuck.

for each item in list
    check item does not equal item currently being checked
    if item match
    then add one to item (quantity?) and delete duplicate element.
    else continue search.

All I can think of is that I need to use a while loop nested inside my for loop and potentially add a new field somewhere that counts the quantity.

And here is how do to the exact same thing using Java 8 streams:

// java8 shorthand for creating a fixed list.
List<String> items = Arrays.asList("Bread","Cheese","Coke","Coke","Cheese","Crisps");
Map<String, Long> results = 
    items.stream().collect(
        groupingBy(
            Function.identity(), // the value of each string
            Collectors.counting()));// counts duplicates
System.out.println(results);
List<String> items = new ArrayList<>();
items.add("Bread");
items.add("Cheese");
items.add("Coke");
items.add("Coke");
items.add("Cheese");
items.add("Crisps");

Map<String, Integer> counts = new HashMap<>();
for (String item : items) {
    Integer count = counts.get(item);
    if (count == null) {
        count = new Integer(0);
    }
    count = count + 1;
    counts.put(item, count);
}

System.out.println(counts);

Output:

{Crisps=1, Coke=2, Cheese=2, Bread=1}

A Map associates a key with a value. You put things in with the key and get them out with the key. Keys in the Map are unique. In this example the key is the item and the value is the count of times that item has been seen. We iterate over the items list. For each item we get its count out of the Map. (If this is the first time we create a new 0 count for the item.) We increment the count for that item and, put it back in the Map and carry on until we have traversed the list.

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