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

Time:08-05

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"
}

CodePudding user response:

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

CodePudding user response:

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.

CodePudding user response:

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

private boolean check(List<String> states) {
    return Collections.min(states).equals(Collections.max(states)) &&
           Collections.min(states).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".

  • Related