我如何获得独特类别的名称

how do I get the names of unique categories

我有一个 ArrayList,其中包含每条记录的以下详细信息,例如:NameCategory

其中,名称 是食品名称,类别 是食品类别

所以在 Arraylist 我有 multiple food items forsame Category`,比如:

Item Name : Samosa
Item Category : Appetizer

Item Name : Cold Drink
Item Category : Drinks

Item Name : Fruit Juice
Item Category : Drinks

现在我只想获取唯一类别的名称

这是我的代码:

Checkout checkOut = new Checkout();
checkOut.setName(strName);
checkOut.setCategory(strCategory);

checkOutArrayList.add(checkOut);

您可以将类别收集到 Set. Using s TreeSet 在这种情况下有一个很好的好处,因为它还会按字母顺序对类别进行排序,这可能适合需要显示它们的 GUI。

Set<String> uniqueCategories = new TreeSet<>();

// Accumulate the unique categories
// Note that Set.add will do nothing if the item is already contained in the Set.
for(Checkout c : checkOutArrayList) {
    uniqueCategories.add(c.getCategory());
}

// Print them all out (just an example)
for (String category : uniqueCategories) {
    System.out.println(category);
}

编辑:
如果您使用的是 Java 8,则可以使用流式语法:

Set<String> uniqueCategories = 
    checkOutArrayList.stream()
                     .map(Checkout::getCategory)
                     .collect(Collectors.toSet());

或者,如果您想将其收集到 TreeSet 中并立即对结果进行排序:

Set<String> uniqueCategories = 
    checkOutArrayList.stream()
                     .map(Checkout::getCategory)
                     .collect(Collectors.toCollection(TreeSet::new));