我有一个代码,可以按要求工作,但我想用 Java 8 重写它。
此代码将生成一个 map 。每个列表项都将分配给它所有的服务器。
public static Map<String, List<String>> agg(){
List<String> list = Arrays.asList("Item A", "Item B", "Item C");
List<String> servers = Arrays.asList("Server A", "Server B", "Server C", "Server D");
Map<String, List<String>> map = new HashMap<>();
for (int i = 0; i < list.size(); i++) {
ArrayList<String> temp = new ArrayList<>();
for (int j = 0; j < servers.size(); j++) {
temp.add(servers.get(j));
}
map.put(list.get(i), temp);
}
return map;
}
输出
Item C ::[Server A, Server B, Server C, Server D]
Item B ::[Server A, Server B, Server C, Server D]
Item A ::[Server A, Server B, Server C, Server D]
什么是 lambda 等价物?
最佳答案
让我们在将代码转换为 lambda 表达式之前简化代码
public static Map<String, List<String>> agg(){
List<String> list = Arrays.asList("Item A", "Item B", "Item C");
List<String> servers = Arrays.asList("Server A", "Server B", "Server C", "Server D");
Map<String, List<String>> map = new HashMap<>();
for (int i = 0; i < list.size(); i++) {
map.put(list.get(i), new ArrayList<>(servers));
}
return map;
}
我只是简化了创建数组副本的过程。
Java 8 中从一种数据形式转换为另一种数据形式的管道包含以下步骤:
- 流
- 映射(从一种形式转换为另一种形式)
- 减少(过滤掉不需要的值)
- 收集(收集结果)
因为你的数据不需要转换,只是在不同的结构中收集,所以不需要map和reduce
public static Map<String, List<String>> agg(){
List<String> list = Arrays.asList("Item A", "Item B", "Item C");
List<String> servers = Arrays.asList("Server A", "Server B", "Server C", "Server D");
Function<String, String> keyFunction = key -> key;
Function<String, List<String>> valueFunction = key -> new ArrayList<>(servers);
return list.stream()
.collect(Collectors.toMap(keyFunction, valueFunction));
}
这些函数可以内联,结果将是:
public static Map<String, List<String>> agg(){
List<String> list = Arrays.asList("Item A", "Item B", "Item C");
List<String> servers = Arrays.asList("Server A", "Server B", "Server C", "Server D");
return list.stream()
.collect(Collectors.toMap(key -> key, key -> new ArrayList<>(servers)));
}
关于java - 在 Java 8 中编写以下代码的可能方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54844590/