Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnsupportedOperationException When Inserting into Map

I am using the Spark's collectAsMap function [Spark CollectAsMap to obtain a Map. In this map, when I do the put operation I am getting the following exception:

ERROR ApplicationMaster: User class threw exception: java.lang.UnsupportedOperationException
java.lang.UnsupportedOperationException
    at java.util.AbstractMap.put(AbstractMap.java:209)

Is the map obtained from collectAsMap unmodifiable?

like image 409
Sanchay Avatar asked Jan 25 '18 12:01

Sanchay


People also ask

How do I fix UnsupportedOperationException?

The UnsupportedOperationException can be resolved by using a mutable collection, such as ArrayList , which can be modified. An unmodifiable collection or data structure should not be attempted to be modified.

Which method is used to insert an entry in the map?

HashMap. put() method of HashMap is used to insert a mapping into a map. This means we can insert a specific key and the value it is mapping to into a particular map.


1 Answers

I assume you are working in Java. You are getting this error because in java spark, collectAsMap returns a java wrapper around a scala map. In Spark 2.2, this wrapper is a custom class defined in this source file. As you can see, it does not define the put method, hence your error.

A workaround could be to simply copy the map into a java HashMap as follows

List<Tuple2<Integer, Integer>> list = new ArrayList<>();
list.add(new Tuple2<>(1,2));
list.add(new Tuple2<>(3,4));
Map<Integer, Integer> map = sc.parallelize(list)
    .mapToPair( x -> x )
    .collectAsMap();
    
Map<Integer, Integer> newMap = new HashMap<>(map);
newMap.put(7, 8);
System.out.println(newMap);

That yields the expected {1=2, 3=4, 7=8}.

like image 54
Oli Avatar answered Sep 20 '22 13:09

Oli