mayank bisht :
I have a code, which is working as required, but I want to re-write it in Java 8.
This code will produce a map.Each list item will have all the servers allocated to it.
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;
}
Output
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]
What would be the lambda equivalent?
nucandrei :
Let's simplify code before converting it to lambda expressions
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;
}
I just simplified creating an array copy.
The pipeline to convert from a form of data to another in Java 8 contains the following steps:
- stream
- map (convert from a form to another)
- reduce (filter out unwanted values)
- collect (collect results)
Because your data does not need to be converted, just collected in a different structure, map and reduce are not needed
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));
}
Those functions can be inlined and the result would be:
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)));
}