2015-07-22 58 views
1

我有一个ArrayList中,我对每个记录下详细信息,如独特的类别的名称:NameCategory我怎么

其中,名称是食品项目名称和类别是食品项目类别

所以在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 

现在我只是想获得独特的类别名称仅

这里是我的代码:

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

checkOutArrayList.add(checkOut); 
+0

你的问题是什么? – Karakuri

+0

问题标题与您在代码中尝试做的不同。我很困惑...:/ – DroidDev

+0

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

回答

5

你可以收集类别为Set。在这种情况下使用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)); 
+0

非常感谢你,如果我想知道一些独特的类别,例如:2 – Oreo

+1

@Oreo Set仍然是一个集合 - 只需调用它的size()方法即可。 – Mureinik

+0

最后一个问题,我做了独特的分类全球但无法使用字符串类作为全球性在我的课,得到:类无法解析到类型 – Oreo