java - 在另一个 lambda 中返回的 lambda 应该是什么
问题描述
所以,我有一个这样的代码摘录(接受一个字符串并将其分为键和值参数)
Files.lines(Paths.get("src/main/files/end.log")).forEach( (p) ->
chart.computeIfPresent(p.substring(0,2), (k, v) -> {
try {
v.setEndTime(p.substring(3));
} catch (ParseException e) {
e.printStackTrace();
}
}));
但我真的不知道我应该在第二个 lambda 中返回什么,因为这两种变体都不起作用。或者它应该工作吗?
解决方案
假设chart
是 aMap
并且computeIfPresent是一个将key
andBiFunction
作为参数的方法
default V computeIfPresent(K key,
BiFunction<? super K,? super V,? extends V> remappingFunction)
如果指定键的值存在且非空,则尝试在给定键及其当前映射值的情况下计算新映射。
因此,此方法用于为 map 中的现有键计算新值,因此BuFunction
将其key,oldvalue
作为参数,返回值将是该键的新计算值
例子 :
Map<String, String> map = new HashMap<String, String>();
map.put("10", "Deadpool");
System.out.println(map); //{10=Deadpool}
现在计算新的值来10
使用computeIfPresent
map.computeIfPresent("10", (key,oldVal)->"Iron Man");
System.out.println(map); // {10=Iron Man}
因此,在您的代码中,您必须返回需要与键关联的新值
Files.lines(Paths.get("src/main/files/end.log")).forEach( (p) ->
chart.computeIfPresent(p.substring(0,2), (k, v) -> {
try {
v.setEndTime(p.substring(3));
} catch (ParseException e) {
e.printStackTrace();
}
//return value for key p.substring(0,2)
}));
推荐阅读
- azure-devops - 为什么 Azure-DevOps 用户看不到其他用户?
- sql - 如何修复sql中连接表的错误计数
- python - 战舰但无法定义
- reactjs - 如何在 React Native 中仅动态增加一个部分的高度
- c# - ASP.NET CORE 3.0 中的 IHtmlHelper - 获取属性值的正确方法是什么?
- java - 如何使用 JSTL 在 jsp 中迭代 foreach
- ios - Coredata 合并关系而不是覆盖它
- java - Selenium Webdriver - 错误
- google-maps - 使用矩形位置偏差的 Google Places API 附近搜索
- android - 如何在 android studio 中调试 React Native 原生模块?