Java 基于android中某些条件的ArrayList过滤器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21281553/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:52:15  来源:igfitidea点击:

ArrayList filter based on some condition in android

javaandroid

提问by user3061048

I have an ArrayListin android which contains several names. Suppose user typed R, so I want to calculate how many names are there in the ArrayListwhich starts with R. for example if arraylist contains Ashok, Bimal, Ram, Raju, sunita then it should return 2 as there are 2 names starts with R

我有一个ArrayListin android,其中包含多个名称。假设用户输入了 R,所以我想计算其中有多少个名字ArrayList以 R 开头。例如,如果 arraylist 包含 Ashok、Bimal、Ram、Raju、sunita,那么它应该返回 2,因为有 2 个名字以 R 开头

采纳答案by user543

    int count = 0;
    ArrayList<String> _list;//ur arraylist with names
    for (String names : _list) {
        if (names.startsWith("R")) {
            count++;
        }

    }
    System.out.println(count);

回答by doorstuck

Iterate through the ArrayList and increment an integer variable when your check returns true.

遍历 ArrayList 并在检查返回 true 时增加一个整数变量。

回答by Gaurav Gupta

    ArrayList<String> list = new ArrayList<String>();
    list.add("Ashok");
    list.add("Bimal");
    list.add("Ram");
    list.add("Raju");
    list.add("sunita");
    int count  = 0;
    for(String s: list){
        if(s.startsWith("R")){
            count++;
        }
    }
    System.out.println(count);

回答by DroidDev

In your onCreate method

在您的 onCreate 方法中

int countToShow=counterMethod(character);
TextView  showCount=(TextView)findViewById(idOfYourTextView);
showCount.setText(String.valueOf(count));

Make another method in your activity as follow:-

在您的活动中制作另一种方法,如下所示:-

public int counterMethod(String character){
    int count=0;
    for(int i=0; i<arrayListName.size();i++)
    {
        String name=arrayListName.get[i];
        if(name.startswith(character))
            count++;
    }
return count;
}

回答by suresh

Try below code....

试试下面的代码....

enter code here
List<String> list = new ArrayList<String>();
list.add("How are you");
list.add("How you doing");
list.add("Joe");
list.add("Mike");

 Collection<String> filtered = Collections2.filter(list,
Predicates.containsPattern("How"));
 print(filtered);