【问题标题】:Java 8, how to add filtering and mapping into Collectors.toMap()Java 8,如何在 Collectors.toMap() 中添加过滤和映射
【发布时间】:2021-09-13 04:47:14
【问题描述】:
protected Map<String, String> test(List<String> ids) {
    return ids
          .stream()
          .map(e -> fun1(e, "1"))
          .filter(out -> out.length() == 3)
          .collect(Function.identity(), ______) (what should i write here, if I want the out put of fun1, writing out here dose not work)
} 
public String fun1(String one, String two) {
    return one + two;
}

简单输入:("1", "23", "34", "6")

那么输出应该是 {("23", "233"), ("34","343")}

原因是“23”“34”加“3”,长度为3,然后放入map中

这是 sudo 代码,不是我使用的真实案例。所以我尝试做映射过滤然后收集到映射,但是对于那里的空白我不知道如何引用 Fun1 的输出。我知道 Java 9 有一些使用过滤的解决方案。 Java 8 的任何解决方案

【问题讨论】:

  • “使用过滤”是什么意思?你能提供示例输入和输出吗?
  • 如果您尝试将ids 中的原始字符串映射到它们的fun1 输出,那么您需要在运行map() 时保留这两个值。否则,请跳过 map,但您会错过过滤器。
  • 不,没有真正的 Java 8 解决方案。在流中进行过滤,而不是在收集器中。
  • 我假设你的映射中的键是映射前的值,而值部分是映射后的对象?但是一旦你使用fun1 映射它,Function.identity() 指的是映射值而不是原始值。
  • 你能看看输入和输出吗,这可能有助于理解我想要做什么

标签: java filter java-stream


【解决方案1】:

要将List 的原始值映射到应用fun1() 的结果中,您必须将map 每个元素映射到一对元素。例如,您可以使用java.util.AbstractMap.SimpleEntry 类。

public class Test
{
    public String fun1(String one, String two) {
        return one + two;
    }

    protected Map<String, String> test(List<String> ids) {
        return ids.stream()
                  .map(e -> new SimpleEntry<String,String>(e, fun1(e, "3")))
                  .filter(e -> e.getValue ().length() == 3)
                  .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
    } 

    public static void main (String[] args) throws Exception
    {
        Test instance = new Test ();
        System.out.println(instance.test (List.of ("1", "23", "34", "6")));
    }
}

输出:

{23=233, 34=343}

【讨论】:

  • 感谢您的反馈。从最后一行获取错误(Map.Entry :: getKey)
  • 错误信息:不能从静态上下文引用非静态方法
  • @shuangquanfu 这很奇怪。代码为我通过了编译。你import java.util.AbstractMap.SimpleEntry;了吗?
  • 是的,我确实添加了该导入
  • @shuangquanfu 你确定你使用的是答案中发布的确切代码吗?请尝试编辑后的答案(我将方法放在一个类中),以确保您没有任何导致问题的额外代码。
【解决方案2】:
public static Map<String, String> test(List<String> ids) {
    return ids.stream()
              .filter(id -> fun1(id, "3").length() == 3)
              .collect(Collectors.toMap(Function.identity(), id -> fun1(id, "3")));
}

private static String fun1(String one, String two) {
    return one + two;
}

【讨论】:

    猜你喜欢
    • 2018-08-26
    • 1970-01-01
    • 2018-01-01
    • 2017-01-20
    • 2019-01-08
    • 2021-05-10
    • 2017-04-08
    • 2021-09-02
    • 2014-06-06
    相关资源
    最近更新 更多