0

I have Avro generated Map that is with Map<CharSequence, CharSequence> type. But my existing method requires Map<String, String> parameter. How can I change Map<CharSequence, CharSequence> to Map<String, String> parameter?

public void someMethod(AvroType avroGenObj){
  myMapMethod(avroGenObj.getInput()) // compile error as getInput returns Map<CharSequence, CharSequence>
}


private void myMapMethod(Map<String, String> map){

// to something

}
ever alian
  • 1,028
  • 3
  • 15
  • 45

2 Answers2

1

You can iterate the map and put each key-value pair in a new map, while toString()-ing them.

Map<CharSequence, CharSequence> map = ...;
Map<String, String> resultMap = new HashMap<>();
for (Map.Entry<CharSequence, CharSequence> entry : map.entrySet()) {
  resultMap.put(entry.getKey().toString(), entry.getValue().toString());
}

Or you can do the same using Stream.

Map<CharSequence, CharSequence> map = ...;
Map<String, String> resultMap = map.entrySet()
      .stream()
      .collect(Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue().toString()));
Chaosfire
  • 4,818
  • 4
  • 8
  • 23
1

It is possible to cause the Avro schema generator to use String instead of CharSequence as the mapping for an Avro string; see How to generate fields of type String instead of CharSequence using Avro?.

Apparently, you can also change the type that Avro uses to represent a string in Java on a per-type basis; see Avro Schema - what is "avro.java.string": "String" and https://stackoverflow.com/a/35727432/139985. However, this can be a source of problems. So beware.

If neither of these approaches are going to work for you, then you will need to do a conversion as per @ChaosFire's answer.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216