Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!eternal-september.org!feeder.eternal-september.org!mx04.eternal-september.org!.POSTED!not-for-mail From: Eric Sosman Newsgroups: comp.lang.java.programmer Subject: Re: exporting a HashMap Date: Sun, 15 Jan 2012 12:01:55 -0500 Organization: A noiseless patient Spider Lines: 39 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Injection-Date: Sun, 15 Jan 2012 17:02:01 +0000 (UTC) Injection-Info: mx04.eternal-september.org; posting-host="HSlJAUb3pGXi3i7ZL/HoAw"; logging-data="11032"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX19X6e2kqN5Hyrjz/YGFwcxL" User-Agent: Mozilla/5.0 (Windows NT 5.1; rv:9.0) Gecko/20111222 Thunderbird/9.0.1 In-Reply-To: Cancel-Lock: sha1:BFa0oaLhhU4y//N7S0XrOWTZZyw= Xref: x330-a1.tempe.blueboxinc.net comp.lang.java.programmer:11351 On 1/15/2012 11:30 AM, Roedy Green wrote: > What is best code to export key-value pairs from a HashMap into some > structure in key-value order. > > One possible way is to extract the keys, sort them, then look up the > values. That strikes me as infantile. Surely there is a better way. > > The best I can think of is to invent a Pair dummy class, extract the > fields from an Entry into the two fields, and sort them in an array. > > Part of the problem is generics and arrays don't mix. Why invent a Pair when Map.Entry already holds the data? Just typed in, unchecked: Map map = ...; List> entries = new ArrayList>(map.entrySet()); Collections.sort(entries, new Comparator>() { @Override public int compare(Map.Entry e1, Map.Entry e2) { return e1.getKey().compareTo(e2.getKey()); } }); for (Map.Entry e : entries) { ... } There's scary Javadoc about the longevity of Map.Entry, but as long as the underlying Map isn't changed all should be well. Another approach is to use a SortedMap, either ab initio or as a substitute for the List-and-sort above: Map map = ...; SortedMap map2 = new TreeMap(map); for (Map.Entry e : map2.entrySet()) { ... } -- Eric Sosman esosman@ieee-dot-org.invalid