Map 8的Java 8流<string,set <string =“”>&gt;

时间:2016-11-16 18:56:04

标签: java java-8 java-stream

我有一张地图&lt;整数,设置&lt;整数&gt;取代。我想基于自定义方法完成的一些修改将其转换为整数列表。

现在我正在使用两个for循环,我想知道是否有更好的方法来使用java流

这是我现有的代码:

public myMethod(Map<Integer, Set<Integer>> myMap, String a, int b) {
List<Integer> myIntegerList = new ArrayList<>();
    for (int i: myMap.keySet()) {
        for ( int j: myMap.get(i)) {
            myIntegerList.add(myCustomMethod(i, j, a.concat(b));
        }
    }
}

public Integer myCustomMethod(int x, int y, String result) {
...
...
...

return Integer;
}

我想知道我们是否可以使用java stream()迭代整数集?

2 个答案:

答案 0 :(得分:1)

    List<Integer> myIntegerList = myMap.entrySet().stream()
            .flatMap(myEntry ->
                myEntry.getValue().stream()
                    .map(setEntry -> myCustomMethod(myEntry.getKey(), setEntry, a + b)))
            .collect(Collectors.toList());

答案 1 :(得分:0)

试试这个:

public void myMethod(Map<Integer, Set<Integer>> myMap, String a, String b) {
        List<Integer> myIntegerList = new ArrayList<>();
        for (int i: myMap.keySet()) 
            myIntegerList.addAll(myMap.get(i).stream().map(j -> myCustomMethod(i, j, a.concat(b))).collect(Collectors.toList()));
    }

我将变量“b”更改为String,因为concat需要String(但如果需要 int ,则可以使用方法Integer.toString(b)