Java 8:过滤数组(NxM)以创建Map <string,hashset <string =“”>&gt;

时间:2017-11-22 19:58:33

标签: java arrays lambda java-8 hashmap

我想在Java 8中将NxN数组映射到Map中。

这个想法是每个[i] [0]元素都是一个键,每个[i] [j] j> 0,都是地图中每个键的值列表。

感谢您的帮助。 :)

这是我的班级:

public class GroupingDishes {

    public static void main(String[] args) {

        String[][] dishes = {
                {"Salad", "Tomato", "Cucumber", "Salad", "Sauce"},
                {"Pizza", "Tomato", "Sausage", "Sauce", "Dough"},
                {"Quesadilla", "Chicken", "Cheese", "Sauce"},
                {"Sandwich", "Salad", "Bread", "Tomato", "Cheese"}
        };

        Map<String, HashSet<String>> groupDishes = groupingDishes(dishes);
    }

    public static Map<String, HashSet<String>> groupingDishes(String[][] dishes) {

        Map<String, HashSet<String>> mapFood = new HashMap<>();

        for (int i = 0; i < dishes.length; i++) {

            String food = dishes[i][0];

            for (int j = 0; j < dishes[i].length; j++) {

                if (mapFood.containsKey(food)) {

                    HashSet<String> existingIngredients = mapFood.get(dishes[i][0]);
                    existingIngredients.add(dishes[i][j]);
                    mapFood.put(food, existingIngredients);

                } else {

                    HashSet<String> newIngredient = new HashSet<>();
                    mapFood.put(food, newIngredient);

                }
            }
        }
        return mapFood;
    }
}

2 个答案:

答案 0 :(得分:5)

您可以将String[][]转换为String[]的流, 然后收集到地图, 使用String[]的第一项作为关键字, 其余作为集合的值。

public static Map<String, HashSet<String>> groupingDishes2(String[][] dishes) {
    return Arrays.stream(dishes)
        .collect(Collectors.toMap(
            arr -> arr[0],
            arr -> Arrays.stream(arr).skip(1).collect(Collectors.toCollection(HashSet::new))));
}
是的,我怀疑你真的需要Map<String, HashSet<String>>。 最好将类型更改为Map<String, Set<String>>, 然后,实现也可以更简单地编写。

public static Map<String, Set<String>> groupingDishes(String[][] dishes) {
    return Arrays.stream(dishes)
        .collect(Collectors.toMap(
            arr -> arr[0],
            arr -> Arrays.stream(arr).skip(1).collect(Collectors.toSet())));
}

或者甚至更好,正如@Holger建议的那样,更好的选择,因为skiplimit的流效果不佳,Collectors也没有得到任何提示结果的初始容量“

public static Map<String, Set<String>> groupingDishes(String[][] dishes) {
    return Arrays.stream(dishes)
        .collect(Collectors.toMap(
            arr -> arr[0],
            arr -> new HashSet<>(Arrays.asList(arr).subList(1, arr.length))));
}

答案 1 :(得分:2)

我能想到这个:

import paramiko

hostname = '43.123.231.212'
password = 'passw'
username = 'dosop'
port = 22

gc_path='/home/do//assets/locations.txt'
remotepath='/home/pi/ada.txt'

t = paramiko.Transport((hostname, 22))
t.connect(username=username, password=password, pkey="/home/pi/dos/priv_key"
sftp = paramiko.SFTPClient.from_transport(t)
sftp.get(gc_path, remotepath)