【问题标题】:How to count same value on recyclerview?如何在 recyclerview 上计算相同的值?
【发布时间】:2020-03-26 03:56:37
【问题描述】:

有什么方法可以统计recyclerview上每一项的出现次数吗?

假设我有 recyclerview 项目:

String[] array = {"item1","item1","item2","item2", "item3", "item4"};

预期输出:-

item1  2
item2  2
item3  1
item4  1

我已经创建了 recycleview 适配器,但我不知道如何计算相同的项目。 请帮忙

【问题讨论】:

  • 您可以使用linkedhashmap并将键存储为项目并将其作为值存储。它与recyclerview无关。
  • @Raghunandan 你能给我举个例子吗?
  • 你可以看看下面的例子。唯一的变化是hashmap没有排序。如果你想要有序的项目集使用linkedhashmap

标签: java android arrays sorting android-recyclerview


【解决方案1】:

这是你要找的功能

public void countEntries(String[] items) {
    HashMap itemToCountMap = new HashMap<String, Integer>();
    for (String item : items) {
        if (itemToCountMap.containsKey(item)) {
            Integer current = (Integer) itemToCountMap.get(item);
            itemToCountMap.put(item, current + 1);
        } else {
            itemToCountMap.put(item, 1);
        }
    }

    // Key - is the string
    // Value - is the number of repetitions
    itemToCountMap.forEach((key, value) -> System.out.println("key: "+key+" value:"+value));
}

现在您只需要从recyclerView.adapter 获取物品(如果您的物品是公开的)

String[] items = recyclerView.getAdapter().getItems()
countEntries(items)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-28
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    • 2019-02-01
    相关资源
    最近更新 更多