首页 > 解决方案 > 将 HashMap 值变量与其他变量进行比较 (Java 8 - Streams)

问题描述

使用 Java 8 中的流可以更清晰地编写此方法吗?

public static boolean doCompareEmail( UserDataAttribute data )
{

    Map<String, User> users = loadUsersByFilter();

    for( Map.Entry<String, User> user : users.entrySet( ) )
    {
        if( user.getKey( ).equals( data.getValue() ) )
        {
            return !data.getEmail().equals( user.getValue( ).getEmail() );
        }
    }
    return false;
}

标签: javajava-stream

解决方案


采用.anyMatch()

return users.entrySet().stream()
                       .anyMatch(u -> u.getKey().equals(data.getValue())
                                      && !data.getEmail().equals(u.getValue().getEmail()));

在这里,您的 if 条件可以简化为

if( user.getKey().equals( data.getValue()) 
          && !data.getEmail().equals( user.getValue().getEmail()) ){
    return true;
}

推荐阅读