gpt4 book ai didi

Java:将 lambda 存储为值的映射

转载 作者:行者123 更新时间:2023-12-02 13:04:58 24 4
gpt4 key购买 nike

我想学习 Java 的“较新”语法和 API 中的可能性。我所说的较新是指 10+(比如说 10-13)。它主要围绕 lambda 声明并存储符合与映射中的值相同签名的不同实现。由于最近我主要与 Gosu 合作,我可以提供以下片段:

var longInput = 10000000L

new LinkedHashMap<String, block(long) : long>( {
"byte" -> (\x -> x as byte as long),
"short" -> (\x -> x as short as long),
"int" -> (\x -> x as int as long),
"long" -> (\x -> x as long as long)
}).eachKeyAndValue(\key, value ->
print("${longInput} ${value(longInput) == longInput ? "can" : "cannot"} be converted to ${key}")
)

我可以在 Java 10 中进行类似的操作:

import java.util.*;

public class Test {
public static void main(String[] args) {
long longInput = 10000000L;

var conversions = new LinkedHashMap<String, Conversion<Long>>();
conversions.put("byte", (x) -> (long) (byte) x.longValue());
conversions.put("short", (x) -> (long) (short) x.longValue());
conversions.put("int", (x) -> (long) (int) x.longValue());
conversions.put("long", (x) -> (long) (long) x.longValue());

conversions.forEach((key, value) -> {
System.out.printf("%d %s be converted to %s%n", longInput, value.convert(longInput) == longInput ? "can" : "cannot", key);
});
}
}

interface Conversion<T> {
T convert(T input);
}

我的问题:

  1. 是否可以在没有命名接口(interface)的情况下通过类似 Gosu 中的“匿名”函数方式来完成?
  2. 还有什么可以让 Java 中的代码更加简洁吗?

更新:这只是一些围绕代码的游戏,其目的是将原始 long 类型双重转换为较小类型并返回。灵感来自https://www.hackerrank.com/challenges/java-datatypes/problem 。所以从我的角度来看,我想留下来。

使用答案,我当前的 Java 10 代码将如下所示:

public class Test { 
public static void main(String[] args) {
var longInput = 10000000L;

new LinkedHashMap<String, UnaryOperator<Long>>() {{
put("byte", (x) -> (long) (byte) x.longValue());
put("short", (x) -> (long) (short) x.longValue());
put("int", (x) -> (long) (int) x.longValue());
put("long", (x) -> (long) (long) x.longValue());
}}.forEach((key, value) -> {
System.out.printf("%d %s be converted to %s%n", longInput, value.apply(longInput) == longInput ? "can" : "cannot", key);
});
}
}

最佳答案

Could it be done without having a named interface but in similar 'anonymous' function way like in Gosu?

Java 已经有一个与您定义的类似的FunctionalInterface。您可以使用UnaryOperator<Long>您的值(value)观Map .

Anything else that could make this more concise in Java?

我认为这读起来更好:

Map<String, UnaryOperator<Long>> conversions = new LinkedHashMap<>();
conversions.put("byte", a -> (long) a.byteValue());
conversions.put("short", a -> (long) a.shortValue());
conversions.put("int", a -> (long) a.intValue());
conversions.put("long", a -> a); // UnaryOperator.identity()

关于Java:将 lambda 存储为值的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59426163/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com