chrisrhyno2003 chrisrhyno2003 - 23 days ago 6
Java Question

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

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() ?

Answer

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)