java map 无法解析的编译问题,Java 8 Lambda,过滤器HashMap,无法解析方法

I'm kinda new to Java 8's new features. I am learning how to filter a map by entries. I have looked at this tutorial and this post for my problem, but I am unable to solve.

@Test

public void testSomething() throws Exception {

HashMap map = new HashMap<>();

map.put("1", 1);

map.put("2", 2);

map = map.entrySet()

.parallelStream()

.filter(e -> e.getValue()>1)

.collect(Collectors.toMap(e->e.getKey(), e->e.getValue()));

}

However, my IDE (IntelliJ) says "Cannot resolve method 'getKey()'", thus unable to complile:

6RRX2.png

Neither does this help:

nyMUU.png

Can anyone help me to solve this issue?

Thanks.

解决方案

The message is misleading but your code does not compile for another reason: collect returns a Map not a HashMap.

If you use

Map map = new HashMap<>();

it should work as expected (also make sure you have all the relevant imports).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 8引入了Function接口和Lambda表达式,这些新特性使得函数式编程变得更加容易和灵活。 Function接口是一个函数式接口,它定义了一个接受一个参数并返回一个结果的函数。它有一个抽象方法apply(),这个方法接受一个参数并返回一个结果。Function接口有多个默认方法可以组合成复杂的函数链,比如andThen()和compose()方法Lambda表达式是一种可以代替匿名内部类的语法,它可以用来创建函数式接口的实例。Lambda表达式由三个部分组成:参数列表、箭头符号和方法体。Lambda表达式的参数列表和方法体可以根据上下文自动推断,这使得代码更加简洁易读。 下面是一个使用Function和Lambda表达式的示例代码: ``` Function<Integer, Integer> square = x -> x * x; int result = square.apply(5); // result = 25 ``` 这个代码定义了一个Function接口的实例square,它接受一个整数参数并返回它的平方。然后我们可以调用这个实例的apply()方法来计算5的平方,结果为25。 Lambda表达式可以用来代替匿名内部类,使得代码更加简洁易读。比如下面这个代码: ``` Runnable runnable = new Runnable() { @Override public void run() { System.out.println("Hello, world!"); } }; ``` 可以使用Lambda表达式来简化为: ``` Runnable runnable = () -> System.out.println("Hello, world!"); ``` 这个代码定义了一个Runnable接口的实例runnable,它的run()方法会输出一条消息。Lambda表达式的箭头符号左侧没有参数,因为run()方法不接受任何参数。箭头符号右侧的方法体只有一条语句,因此可以省略大括号和分号。 总之,Java 8的Function和Lambda表达式为函数式编程带来了更加灵活和易用的工具,使得Java程序员可以更加方便地编写函数式风格的代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值