java - 将 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;
}
解决方案
采用.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;
}
推荐阅读
- wpf - 添加到 SyncHash 的 Powershell WFP 对象不会传递到不同的运行空间
- java - Java A* 算法找不到任何路径
- javascript - 如何将对象中的数组值附加为属性和值?
- excel - 如何使用 INDEX、MATCH、SEARCH 返回整个单元格内容的完全匹配?
- smartcontracts - 我的智能资产的 Base64 代码在测试网上工作,但脚本在创建真实资产时出现语法错误。有任何想法吗?
- html-table - 自定义元素如何拥有多个组件
- apache-beam - Apache Beam Fault Tolerance 如何在全局 Windows 上工作?
- arrays - 如何使用 json 对象数组初始化 JSONModel?
- ios - 如何使用 SDL2 在 iOS 上请求全屏窗口
- javascript - 在 tabview 标签中加载 wiki 页面(生成的 javascript)时出现问题