首页 > 解决方案 > 在另一个 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 中返回什么,因为这两种变体都不起作用。或者它应该工作吗?

标签: javalambda

解决方案


假设chart是 aMap并且computeIfPresent是一个将keyandBiFunction作为参数的方法

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)
        }));

推荐阅读