Pregunta

I have a method that returns a generic List. It can either be List<Map> or List<List> depending on the way the method executes.

//sendthis can be either be List<Map> or List<List>
List sendthis = myClass.myMethod();

I'm using Apache thrift to send this List from the server to the client(python). I need the list to be a List<Map> at the client side. Thrift doesn't allow heterogeneous collections so I need to convert the list sendthis to a List<Map>.

In my case myMethod() returns the List only as a List<Map> but I cannot send it using thrift because thrift expects a List<Map> and not a List.

Is there any way to convert sendthis to a List<Map> without iterating over the original list and copying to a new one, as the list can contain tens of thousands of entries.

NOTE

I tried simply casting it to the required type but with no success.

EDIT

myMethod()'s definition cannot be changed.

¿Fue útil?

Solución

Thrift doesn't allow heterogeneous collections

Yes and no.

union Whatever {
  1 :  Foo foo
  2 :  Bar bar
}

type list<Whatever>  HeterogeneousList

Now you have a list which can hold Foos along with Bars. How cool is that?

Otros consejos

Since all classes in java extend java.lang.Object you can simply define the list like this:

List<? extends Object>

Alternatively, you can always poll your list and check its first argument to determine the true nature of the list. Since you are working with raw types, you will have no remedy but to get some warnings suppressed (once you are sure of what you are doing).

This is an idea of how it could work:

List<?> unknown = getUnknowList();
if(!unknown.isEmpty()){
    Object first = unknown.get(0);
    if(first instanceof List){

        @SuppressWarnings("unchecked")
        List<List<?>> data = (List<List<?>>) unknown;
        doWhatYouWannaDoWithLists(data);

    } else if(first instanceof Map){

        @SuppressWarnings("unchecked")
        List<Map<?,?>> data = (List<Map<?,?>>) unknown;
        doWhatYouWannaDoWithMaps(data);

    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top