Casting LinkedHashMap to Complex Object

You can use ObjectMapper.convertValue(), either value by value or even for the whole list. But you need to know the type to convert to: POJO pojo = mapper.convertValue(singleObject, POJO.class); // or: List<POJO> pojos = mapper.convertValue(listOfObjects, new TypeReference<List<POJO>>() { }); this is functionally same as if you did: byte[] json = mapper.writeValueAsBytes(singleObject); POJO pojo = mapper.readValue(json, … Read more

LinkedHashMap in .NET

Just to clarify a bit for readers: LinkedHashMap only behaves that way when built with one particular constructor overload. Normally the elements are maintained in insert order. (This feels a little odd to me, but never mind.) I don’t believe there’s any such class in .NET. It wouldn’t be too hard to build one, using … Read more

Iterating through a LinkedHashMap in reverse order

The question requires a LinkedHashMap in reverse order, some answers suggesting using a TreeSet but this will reorder the map based upon the key. This solution allows the iteration over the original LinkedHashMap not the new ArrayList as has also been proposed: List<String> reverseOrderedKeys = new ArrayList<String>(linkedHashMap.keySet()); Collections.reverse(reverseOrderedKeys); for (String key : reverseOrderedKeys) { RecordItemElement … Read more

Sorting LinkedHashMap

List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(map.entrySet()); Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() { public int compare(Map.Entry<String, Integer> a, Map.Entry<String, Integer> b){ return a.getValue().compareTo(b.getValue()); } }); Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>(); for (Map.Entry<String, Integer> entry : entries) { sortedMap.put(entry.getKey(), entry.getValue()); }

Java LinkedHashMap get first or last entry

The semantics of LinkedHashMap are still those of a Map, rather than that of a LinkedList. It retains insertion order, yes, but that’s an implementation detail, rather than an aspect of its interface. The quickest way to get the “first” entry is still entrySet().iterator().next(). Getting the “last” entry is possible, but will entail iterating over … Read more