【问题标题】:How can we confirm if all the values in a Map<String, String> are empty [duplicate]How can we confirm if all the values in a Map<String, String> are empty [duplicate]
【发布时间】:2022-12-02 04:42:46
【问题描述】:

I have a Map&lt;String,String&gt; myMap and I'd like to check if all the values in the map are empty strings (""). I found a way to confirm if all thevaluesare null: myMay.values().stream.allMatch(Objects::inNull) but I need to check if all the values are empty strings (""). Any ideas? Thanks

【问题讨论】:

    标签: java


    【解决方案1】:

    You can use the allMatch method on the map's values stream to check if all the values are empty strings. Here's one way you could do it:

    if (myMap.values().stream().allMatch(value -> value.equals(""))) {
      // all the values in the map are empty strings
    }
    

    Alternatively, you could use the isEmpty method to check if a string is empty, like this:

    if (myMap.values().stream().allMatch(String::isEmpty)) {
      // all the values in the map are empty strings
    }
    

    Note that both of these solutions assume that the values in the map are strings. If the values in the map could be null, you should add a null check before checking if the string is empty, like this:

    if (myMap.values().stream().allMatch(value -> value != null && value.equals(""))) {
      // all the values in the map are empty strings
    }
    

    I hope this helps! Let me know if you have any other questions.

    【讨论】:

      【解决方案2】:

      Alternatively, you can use static method Predicate.isEqual(), which expects a reference to the target object for equality comparison (an empty string in this case).

      boolean allEmpty = myMap.values().stream().allMatch(Predicate.isEqual(""));
      

      【讨论】:

        【解决方案3】:

        You can use allMatch(""::equals)1, or allMatch(Strings::isNullOrEmpty)2if you want to check for strings that are either nullorempty.


        1""::equals is equivalent to o -&gt; "".equals(o), which is functionally equivalent to o -&gt; o.equals("") ; use whichever of these you find most readable

        2or a similar function from another library

        【讨论】:

          猜你喜欢
          • 2022-12-27
          • 2022-12-01
          • 2021-07-18
          • 2022-12-02
          • 2022-12-02
          • 2022-12-27
          • 2022-12-01
          • 2022-12-19
          • 2022-12-02
          相关资源
          最近更新 更多