在java中,我希望以一行流返回Map

xxhby3vn  于 2021-08-20  发布在  Java
关注(0)|答案(3)|浏览(306)

我正在努力改进我的代码,它已经可以工作了,所以我有一个方法返回一个 Map :

public Map<String, String> extractPartitionsValues(java.nio.file.Path marketFile) {

    Map<String, String> map = new HashMap<>();
    for (String p : this.partitions) {
        map.put(p, partitionValueFromFilePath(p, marketFile.toString()));
    }
    return map;
}

我想用stream和collectorstomap在一行中重新运行这个,但我真的不知道,所以我读了doc和我找到的所有内容,但它仍然不起作用,有人能帮我吗。

nbewdwxp

nbewdwxp1#

使用 Collectors.toMap() 具有 identity() 对于键和值的计算:

public Map<String, String> extractPartitionsValues(Path marketFile) {
    return partitions.stream()
      .collect(toMap(identity(), p -> partitionValueFromFilePath(p, marketFile.toString())));
}
i5desfxk

i5desfxk2#

这应该起作用:

Map<String, Object> collect =
                partitions.stream().collect(Collectors.toMap(p -> p, p -> partitionValueFromFilePath(p, marketFile.toString())));
ulmd4ohb

ulmd4ohb3#

这里的要点是从 partitions 领域
如果 partitions 定义为字符串数组, Arrays.stream 应使用: Arrays.stream(this.partitions) .
否则,如果 partitions 是字符串的集合(集合或列表),它有自己的方法 stream() / parallelStream() .
接下来,为了使用 Collectors.toMap 最简单的形式是 partitions 字段应仅包含唯一值。这可以通过应用 .distinct() 对流的操作,如果 partitions 定义为数组或列表。
因此,结果函数可能如下所示: private String[] partitions; :

public Map<String, String> extractPartitionsValues(Path marketFile) {
    String path = marketFile.toString();
    return Arrays.stream(this.partitions)
      .distinct()
      .collect(Collectors.toMap(
          p -> p, p -> partitionValueFromFilePath(p, path)
    ));
}
``` `private List<String> partitions;` ```
public Map<String, String> extractPartitionsValues(Path marketFile) {
    String path = marketFile.toString();
    return this.partitions.stream()
      .distinct()
      .collect(Collectors.toMap(
          p -> p, p -> partitionValueFromFilePath(p, path)
    ));
}
``` `private Set<String> partitions;` ```
public Map<String, String> extractPartitionsValues(Path marketFile) {
    String path = marketFile.toString();
    return this.partitions.stream() // does not contain duplicates
      .collect(Collectors.toMap(
          p -> p, p -> partitionValueFromFilePath(p, path)
    ));
}

还是超载 toMap 使用合并功能可以处理可能的密钥复制:

private Collection<String> partitions; // could be set or list

public Map<String, String> extractPartitionsValues(Path marketFile) {
    String path = marketFile.toString();
    return this.partitions.stream()
      .collect(Collectors.toMap(
          p -> p, 
          p -> partitionValueFromFilePath(p, path), 
          (p1, p2) -> p1 // use the first key
    ));
}

相关问题