我正在使用Spark。 在對scala.Tuple2<K,V>
的RDD進行收集後的火花中,我得到了scala.Tuple2<K,V>
的列表。我想將它轉換爲Java中的HashMap<K,V>
。如何將List <scala.Tuple2>轉換爲java.util.HashMap?
我可以迭代列表並將其添加到我的HashMap,但我正在尋找一個優雅的方式來做到這一點。謝謝!
我正在使用Spark。 在對scala.Tuple2<K,V>
的RDD進行收集後的火花中,我得到了scala.Tuple2<K,V>
的列表。我想將它轉換爲Java中的HashMap<K,V>
。如何將List <scala.Tuple2>轉換爲java.util.HashMap?
我可以迭代列表並將其添加到我的HashMap,但我正在尋找一個優雅的方式來做到這一點。謝謝!
我覺得在的Java最優雅的方式是使用stream
和Collectors
。
可以實現這種方式:
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}
在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}
我在問題中提到了java。 –
你要這樣呢? http://stackoverflow.com/a/33345553/4969370 – Androbin