如何将HashMap(String,ArrayList)转换为3d数组?

时间:2018-05-13 06:36:11

标签: java arrays collections hashmap

我在Hashmap中的输出>是:

House cleaning = [Jack, Maria]
Computer lessons = [Leon, Maria]
Data recovery service = [Leon]
Computer repair = [Jack, Leon]
Handyman = [Jack]

预期输出

[[["Computer lessons"],["Leon","Maria"]], 
 [["Computer repair"],["Jack","Leon"]], 
 [["Data recovery service"],["Leon"]], 
 [["Handyman"],["Jack"]], 
 [["House cleaning"],["Jack","Maria"]]]

订单并不重要。

1 个答案:

答案 0 :(得分:0)

试试这个。

Map<String, List<String>> map = new HashMap<>();
map.put("House cleaning", Arrays.asList("Jack", "Maria"));
map.put("Computer lessons", Arrays.asList("Leon", "Maria"));
map.put("Data recovery service", Arrays.asList("Leon"));
map.put("Computer repair", Arrays.asList("Jack", "Leon"));
map.put("Handyman", Arrays.asList("Jack"));
String[][][] result = map.entrySet().stream()
    .map(e -> new String[][] {
        new String[] {e.getKey()},
        e.getValue().toArray(new String[0])})
    .toArray(String[][][]::new);
for (String[][] row : result)
    System.out.println(Arrays.deepToString(row));

结果是

[[House cleaning], [Jack, Maria]]
[[Computer lessons], [Leon, Maria]]
[[Data recovery service], [Leon]]
[[Computer repair], [Jack, Leon]]
[[Handyman], [Jack]]