java - 将 2 个流转换为一个流和 map()
问题描述
我有一个 StudentLogin 数组,其中名称是键,值是值
"studentLogin" : [
{
"name" : "firstName_key",
"value" : "<actual first Name value>"
},
{
"name" : "lastName_key",
"value" : "<actual last Name value>"
},
....
]
我有一个方法,我将 studentLogin 列表作为输入参数,我需要检查 firstName(key) 和 lastName(key) 是否存在于同一个索引中,如果是,那么我需要连接 firstname 的实际值和来自同一索引的姓氏。
我写了下面的方法,但是使用了两个流,我想把它转换成一个流。
public String convertStudentLoginToFullName(List<StudentLogin> studentLogin) {
if (null != studentLogin) {
String firstName = studentLogin.stream()
.filter(x -> "firstName_key".equalsIgnoreCase(x.getName()))
.map(x->x.getValue())
.findFirst()
.orElse(null);
String lastName = studentLogin.stream()
.filter(x -> "lastName_key".equalsIgnoreCase(x.getName()))
.map(x -> x.getValue())
.findFirst()
.orElse(null);
String fullName=firstName+" "+lastName;
return fullName;
}
}
return null;
}
解决方案
一种方法是将您的列表转换StudentLogin
为Map
第一个:
Map<String, String> studentLoginMap = studentLogin.stream()
.collect(Collectors.toMap(
StudentLogin::getName(),
StudentLogin::getValue(),
(old, new) -> old
))
注意如果有多个StudentLogin
同名的s,我使用merge函数(old, new) -> old
来解决冲突。始终使用与您在原始代码中所做的匹配的旧值 - 取第一个匹配firstName_key
的lastName_key
.
studentLoginMap
现在,如果名字和姓氏都存在,您可以访问和连接的值:
String firstName = studentLoginMap.get("firstName_key");
String lastName = studentLoginMap.get("lastName_key");
if (firstName != null && lastName != null) {
String result = firstName + " " + lastName;
}
推荐阅读
- javascript - 如何在 JSON 文件中搜索以字符串作为 Node.js 中的键的值
- c# - PanGestureRecognizer 在 contentview 中不起作用
- mongodb - 在 mongodb 聚合中计算另一个文档中的项目
- python - 我如何制作一个通过 2 个特定步骤打印列表值的函数(Python)
- javascript - 在具有不同主机/服务器的 2 个不同数据库上的 2 个表之间创建关联 - ER_BAD_DB_ERROR
- ios - Safari 呈现白框。尝试 flexBasis:0 到整个列表
- java - 如何在java中的String数组中找出正确的字符串?
- c# - WinUI3 TabView XAML 不更新视图中的数据绑定
- javascript - 如何在 javascript 中调用 Rails 方法
- c++ - 为什么我不能将数组传递给函数模板?