Ore*_*reo 1 java android unique arraylist
我有一个ArrayList关于每个记录的详细信息,例如:Name和Category
其中,名称是食品项目名称,类别是食品项目类别
所以在Arraylist中我有multiple food items for相同的Category`,如:
Item Name : Samosa
Item Category : Appetizer
Item Name : Cold Drink
Item Category : Drinks
Item Name : Fruit Juice
Item Category : Drinks
Run Code Online (Sandbox Code Playgroud)
现在我只想获得唯一类别的名称
这是我的代码:
Checkout checkOut = new Checkout();
checkOut.setName(strName);
checkOut.setCategory(strCategory);
checkOutArrayList.add(checkOut);
Run Code Online (Sandbox Code Playgroud)
你可以将类别收集到一个Set.TreeSet在这种情况下使用s 有一个很好的奖励,因为它也会按字母顺序对类别进行排序,这可能适合需要显示它们的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);
}
Run Code Online (Sandbox Code Playgroud)
编辑:
如果您使用的是Java 8,则可以使用流式语法:
Set<String> uniqueCategories =
checkOutArrayList.stream()
.map(Checkout::getCategory)
.collect(Collectors.toSet());
Run Code Online (Sandbox Code Playgroud)
或者,如果你想将它收集到一个TreeSet并从结果中获取结果:
Set<String> uniqueCategories =
checkOutArrayList.stream()
.map(Checkout::getCategory)
.collect(Collectors.toCollection(TreeSet::new));
Run Code Online (Sandbox Code Playgroud)