简体   繁体   中英

How to check if string list contains anything other than some value?

If we have two simple lists where one have only one repeating value:

List<String> states = Arrays.asList("Excelent", "Excelent", "Excelent");

and the other one have one different value:

List<String> states = Arrays.asList("Excelent", "Excelent", "Good");

how can I check if list contains anything other than "Excelent" in this case?

It should looks something like:

private boolean check(List<String> states){
    //Some condition where we can say if there is any item not equal to "Excelent"
}

There are many ways to solve it.

You can for example streaming it and filter for values different to Excelent

private boolean check(List<String> states){
    return states.stream()
              .filter(item -> !item.equals("Excelent"))
              .count() > 0;
}

One option is to use Stream.distinct() ( doc ) to first return distinct elements of the stream and then using the result to decide the next step.

You could use an aggregation approach with the help of Collections.min() and Collections.max() :

private boolean check(List<String> states) {
    String minState = Collections.min(states);
    String maxState = Collections.max(states);

    return minState.equals(maxState) && minState.equals("Excelent");
}

The above method checks if the "smallest" string in the list be the same as the largest one (implying only one value), and also it asserts that this one value be "Excelent" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM