Java8中的hashmap条目对流?

时间:2015-08-08 19:29:04

标签: java hashmap java-8 java-stream

Java8中,拥有HashMap<Integer, City> capitals我希望获得由Stream<Map.Entry<Integer, City>, Map.Entry<Integer, City>> capitalPairs过滤的资本对Integer。我怎么能这样做?

示例:capitals = { (1, Amsterdam), (2, Barcelona), (3, Dortmund) }然后(过滤定义为first integer < second integer):

capitalPairs = [
( (1, Amsterdam), (2, Barcelona) ),
( (1, Amsterdam), (3, Dortmund) ),
( (2, Barcelona), (3, Dortmund) ) ]

1 个答案:

答案 0 :(得分:3)

假设您希望first < second所有关键的apirs避免重复组合。

capitals.keySet().stream().flatMap(k1 ->
    capitals.keySet().stream().filter(k2 -> k1 < k2).map(k2 -> Pair.of(k1, k2)))
    // do something with the pair of keys, lookup the city as required.

您可以使用entrySet()而不是keySet()来执行此操作,但这更麻烦。

capitals.entrySet().stream().flatMap(e1 ->
    capitals.entrySet().stream().filter(e2 -> e1.getValue() < e2.getValue()).map(e2 -> Pair.of(e1, e2)))
    // do something with the Pair of entry(s)