【问题标题】:how do I get the names of unique categories如何获取唯一类别的名称
【发布时间】:2015-07-22 06:03:07
【问题描述】:

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

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

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

【问题讨论】:

  • 你有什么问题?
  • 问题标题与您在代码中尝试执行的操作不同。我很困惑...:/
  • 如何获取唯一类别的名称?
  • 将您的类别添加到集合中,例如TreeSet 不允许重复。

标签: java android arraylist unique


【解决方案1】:

您可以将类别收集到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));

【讨论】:

  • 非常感谢,如果我想知道独特类别的数量,例如:2
  • @Oreo 一个 Set 仍然是一个 Collection - 只需调用它的 size() 方法。
  • 最后一个问题,我将 uniqueCategories 设为全局,但无法在我的班级中将 String 类别用作全局,得到:无法将类别解析为类型
  • @Oreo 很难从简短的评论中理解完整的问题。请使用您的实际代码和您遇到的确切错误发布一个新问题。
猜你喜欢
  • 1970-01-01
  • 2016-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-30
  • 1970-01-01
  • 2016-04-26
  • 2017-12-24
相关资源
最近更新 更多