首页 > 解决方案 > 将 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;
  }

标签: javalistcollectionsjava-8java-stream

解决方案


一种方法是将您的列表转换StudentLoginMap第一个:

Map<String, String> studentLoginMap = studentLogin.stream()
    .collect(Collectors.toMap(
        StudentLogin::getName(),
        StudentLogin::getValue(),
        (old, new) -> old
    ))

注意如果有多个StudentLogin同名的s,我使用merge函数(old, new) -> old来解决冲突。始终使用与您在原始代码中所做的匹配的旧值 - 取第一个匹配firstName_keylastName_key.

studentLoginMap现在,如果名字和姓氏都存在,您可以访问和连接的值:

String firstName = studentLoginMap.get("firstName_key");
String lastName = studentLoginMap.get("lastName_key");
if (firstName != null && lastName != null) {
   String result = firstName + " " + lastName;
}

推荐阅读