2016-09-22 302 views
1

我正在使用Spark。 在对scala.Tuple2<K,V>的RDD进行收集后的火花中,我得到了scala.Tuple2<K,V>的列表。我想将它转换为Java中的HashMap<K,V>如何将List <scala.Tuple2>转换为java.util.HashMap?

我可以迭代列表并将其添加到我的HashMap,但我正在寻找一个优雅的方式来做到这一点。谢谢!

+0

你要这样呢? http://stackoverflow.com/a/33345553/4969370 – Androbin

回答

1

我觉得在的Java最优雅的方式是使用streamCollectors

可以实现这种方式:

List<Tuple2<String, String>> list = new ArrayList<>(); 
    list.add(new Tuple2<>("first", "second")); 
    list.add(new Tuple2<>("third", "four")); 
    list.add(new Tuple2<>("five", "six")); 
    list.add(new Tuple2<>("seven", "eight")); 
    list.add(new Tuple2<>("nine", "ten")); 

    System.out.println("List of Tuple2s:" + list); 

    //convert list of tupples to Map with one line 
    Map<String, String> resultMap = list.stream() 
      .collect(Collectors.toMap(Tuple2::_1, Tuple2::_2)); 

    System.out.println("Map of Tuples2s: "+resultMap); 

输出:

List of Tuple2s:[(first,second), (third,four), (five,six), (seven,eight), (nine,ten)] 
    Map of Tuples2s: {nine=ten, third=four, seven=eight, five=six, first=second} 

但对于重复键?当我们添加另一个项目列出,如:list.add(new Tuple2<>("first", "ten"));例外occures:螺纹

异常 “主要” java.lang.IllegalStateException:在 java.util.stream.Collectors.lambda $ throwingMerger $ 0复制 键第二( Collectors.java:133) 在java.util.HashMap.merge(HashMap.java:1253)

如果你不知道你是否能有重复的,你可以这样做:

Map<String, String> resultMap = list.stream() 
      .collect(Collectors.toMap(Tuple2::_1, Tuple2::_2, 
        (x, y) -> { 
         System.out.println("duplicate key!"); 
         return x; 
        })); 

并避免覆盖Map中的项目。

输出:

List of Tuple2s:[(first,second), (third,four), (five,six), (seven,eight), (nine,ten), (first,ten)] 
duplicate key! 
Map of Tuples2s: {nine=ten, third=four, seven=eight, five=six, first=second} 
2

在Scala中,你可以这样做:

scala> import scala.collection.JavaConverters._ 

scala> val tuples = List((1, 2), (2, 3), (4, 5)) 
scala> tuples.toMap.asJava 
res1: java.util.Map[Int,Int] = {1=2, 2=3, 4=5} 
+0

我在问题中提到了java。 –

相关问题