Java 8 stream for Map <String, Set<String>>

你离开我真会死。 提交于 2019-12-14 03:44:47

问题


I have a Map< Integer, Set < Integer > >. I would like to convert it to a list of Integers based on some modification done by a custom method.

Right now I am using two for loops and I wanted to know if there's a better way to do it using java streams

Here's my existing code:

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;
}

I wanted to know if we could iterate through the set of integers using java stream() ?


回答1:


Try this one:

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()));
    }

I change variable "b" to String because concat need String (but if you need int , you can use method Integer.toString(b)




回答2:


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


来源:https://stackoverflow.com/questions/40640114/java-8-stream-for-map-string-setstring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!