Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
554 views
in Technique[技术] by (71.8m points)

java - 如何在recyclerview上计算相同的价值?(How to count same value on recyclerview?)

Is there any method for counting the occurrence of each item on recyclerview ?

(是否有任何方法可以计数recyclerview上每个项目的出现?)

Lets say I have recyclerview items:

(可以说我有recyclerview项目:)

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

expected output :-

(预期产量:-)

item1  2
item2  2
item3  1
item4  1

I already create recycleview adapter, but i don't know how to count the same item.

(我已经创建了recycleview适配器,但是我不知道如何计算同一项目。)

please help

(请帮忙)

  ask by rangga ario translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is the function you are looking for

(这是您要寻找的功能)

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));
}

Now you only need to get items from the recyclerView.adapter (if your items are public)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...