Java 如何获取唯一类别的名称
我有一个Java 如何获取唯一类别的名称,java,android,arraylist,unique,Java,Android,Arraylist,Unique,我有一个ArrayList,其中每个记录都有以下详细信息,比如:Name和Category 其中,名称为食品名称,类别为食品类别 因此,在一个Arraylist中,我有多个相同类别的食物,比如: Item Name : Samosa Item Category : Appetizer Item Name : Cold Drink Item Category : Drinks Item Name : Fruit Juice Item Category : Drinks 现在我只想得到唯一类别
ArrayList
,其中每个记录都有以下详细信息,比如:Name
和Category
其中,名称为食品名称,类别为食品类别
因此,在一个Arraylist中,我有多个相同类别的食物,比如:
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);
您可以将类别收集到一个列表中。在这种情况下,使用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);
}
您可以将类别收集到一个列表中。在这种情况下,使用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);
}
您的问题是什么?问题的标题不同于您在代码中尝试执行的操作。我很困惑…:/如何获取唯一类别的名称?将您的类别添加到一个集合中,例如,该集合不允许重复。您的问题是什么?问题的标题与您在代码中尝试执行的不同。我很困惑…:/如何获取唯一类别的名称?将您的类别添加到一个集合中,例如,该集合不允许重复。非常感谢,如果我想知道唯一类别的数量,例如:2@Oreo集合仍然是一个集合-只需调用其size()
方法即可。最后一个问题,我将uniqueCategories设置为全局,但无法在类中将字符串category用作全局,getting:category无法解析为type@Oreo从一个简短的评论中很难理解整个问题。请用您的实际代码和您得到的确切错误发布一个新问题。非常感谢您,如果我想知道独特类别的数量,如:2@Oreo集合仍然是集合-只需调用其size()
方法即可。最后一个问题,我将uniqueCategories设置为全局,但无法在类中使用字符串类别作为全局,获取:无法将类别解析为type@Oreo从一个简短的评论中很难理解整个问题。请用你的实际代码和你得到的确切错误发布一个新问题。
Set<String> uniqueCategories =
checkOutArrayList.stream()
.map(Checkout::getCategory)
.collect(Collectors.toCollection(TreeSet::new));