javaarraylisthashmaplinkedhashmap

Cast HashMap in LinkedHashMap


I'm getting the results from the database into a List<Map<String, Object>>. The problem the values are not in order, so I thought to cast in a LinkedHashMap, but I get this exception:

 javax.ejb.EJBException: java.lang.ClassCastException: class java.util.HashMap cannot be cast to class java.util.LinkedHashMap (java.util.HashMap and java.util.LinkedHashMap are in module java.base of loader 'bootstrap')

The method is this:

protected EntityManager em;
Query q = em.createNativeQuery("select * from City");
NativeQueryImpl nativeQuery = (NativeQueryImpl) q;
nativeQuery.setResultTransformer(AliasToEntityMapResultTransformer.INSTANCE);
List<LinkedHashMap<String, Object>> r = (List<LinkedHashMap<String, Object>>) nativeQuery.getResultList();
r.stream().forEach(System.out::println);

Does anybody knows how can I print results in order?


Solution

  • Create this class and call it instead of: AliasToEntityMapResultTransformer.INSTANCE

    public class MyTransformer extends AliasedTupleSubsetResultTransformer {
    
    public static final MyTransformer INSTANCE = new MyTransformer();
    
    /**
     * Disallow instantiation of AliasToEntityMapResultTransformer.
     */
    private MyTransformer() {
    }
    
    @Override
    public Object transformTuple(Object[] tuple, String[] aliases) {
        Map result = new LinkedHashMap<>(tuple.length);
    
        for (int i = 0; i < tuple.length; i++) {
            String alias = aliases[i];
            if (alias != null) {
                result.put(alias, tuple[i]);
            }
        }
        return result;
    }
    
    @Override
    public boolean isTransformedValueATupleElement(String[] aliases, int tupleLength) {
        return false;
    }
    
    /**
     * Serialization hook for ensuring singleton uniqueing.
     *
     * @return The singleton instance : {@link #INSTANCE}
     */
    private Object readResolve() {
        return INSTANCE;
    }
    }