问题
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