2016-11-16 138 views
-2

我有一个Map < Integer,Set < Integer>>。我想根据自定义方法所做的一些修改将其转换为整数列表。Java 8 stream for Map <String,Set <String>>

现在我用两个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()迭代整数集合?

+1

现有的代码没有编译。返回类型丢失(应该是'void')并且'a.concat()'不能应用于'int'参数(或许使用'a + b'连接起来,我不会知道)我也假设下一个方法应该被宣布为“公开”整数myCustomMethod(int x,int y,String结果)'。 'Integer'实例应该在'return'之后给出。 –

回答

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” 为字符串,因为CONCAT需要字符串(但如果你需要INT,您可以使用方法Integer.toString(b)

+0

迭代通过map的入口集(比如,chrisrhyno2003的答案)通常被认为是更好的风格,而不是迭代通过键集,然后使用get()来获取每个键的值。你可以有意识地用循环来做这件事('for(Map.Entry > entry:myMap.entrySet())')。 –

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