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
83 views
in Technique[技术] by (71.8m points)

java - How do I find a specific string in a list of strings with similar values

In a list of strings, the individual strings have a bunch of numbers separated by commas.

ex.

List<String> numberGroups = {"55,46,10,0,85,80,67","100,64,70,6","1,23,59,60","5,0,98,54"};

I want to identify numberGroups that only have a single "0".. but my code is finding any "0" and returning all the groups since the others contain a 0 in "100", "70".. etc. I only want to find strings with a single 0 and add that string to a list to return.

Here is what I have -

public static List<String> findGroups(List<String> groups){
        List<String> grp = new ArrayList<>();
        for(String x : groups) {
            if(x.contains("0")) {
                grp.add(x);
            }
        }
        return grp;
    }
`` 
question from:https://stackoverflow.com/questions/65877523/how-do-i-find-a-specific-string-in-a-list-of-strings-with-similar-values

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

1 Reply

0 votes
by (71.8m points)

I don't know what version of Java you are using but if it is at least version 8 you can do the following.

public static List<String> findGroups(List<String> groups){
        List<String> grp = new ArrayList<>();
        for(String x : groups) {
            long count = x.chars().filter(ch -> ch == 'e').count();
            if( count < 2 ) {
                grp.add(x);
            }
        }
        return grp;
    }

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

...