Mayank Bisht:
私は、必要に応じて働いているコードを、持っているが、私は再書き込み、それは、Java 8にしたい
。このコードは、それに割り当てられたすべてのサーバーを持つことになりますmap.Eachリスト項目を生成します。
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]
何がラムダ同等のでしょうか?
nucandrei:
レッツ・簡素化コードラムダ式に変換する前に、
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内の別のデータの形式から変換するために、パイプラインは、次のステップがあります。
- ストリーム
- マップ(別の形式へ変換)
- (不要な値をフィルタリング)を削減
- コレクト(収集結果)
あなたのデータを変換する必要はありませんので、ちょうど異なる構造に集め、マップや軽減は必要ありません
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)));
}