package com.alexbleasdale.example;
import java.text.MessageFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.log4j.Logger;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
/**
* Sorting a Map<String,Long> by Values
*
* @author ableasdale
*
*/
public class TestOrderingMapItems {
private static final Logger LOG = Logger
.getLogger(TestOrderingMapItems.class);
private Map<String, Long> map;
@BeforeClass
public void setUpOnce() throws Exception {
LOG.info("Set up");
map = new HashMap<String, Long>();
map.put("A", 5L);
map.put("B", 4L);
map.put("C", 10L);
map.put("D", 6L);
}
@Test
public void getItemsByKeyInOrder() throws Exception {
List<Map.Entry<String, Long>> resultList = new LinkedList<Map.Entry<String, Long>>(
map.entrySet());
Collections.sort(resultList, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
// Switch o2 and o1 to order from lowest to highest
return ((Comparable<Object>) ((Map.Entry<?, ?>) (o2))
.getValue()).compareTo(((Map.Entry<?, ?>) (o1))
.getValue());
}
});
LOG.info("Ordered list as follows:");
for (Object e : resultList) {
LOG.info(MessageFormat.format("{0} | {1}", ((Entry<?, ?>) e).getKey(), ((Entry<?, ?>) e).getValue()));
}
}
}
Wednesday, December 2, 2009
Java: Sorting a Map by Values
Here's a simple (TestNG) test to demonstrate getting a List of values out of a Map where you'd like the contents to be ordered by Value (not Key)
Subscribe to:
Post Comments (Atom)
Blog Archive
-
▼
2009
(37)
-
►
June
(10)
- Daisy CMS - connecting a JMS listener to the repos...
- Daisy CMS - customising the footer of the editor p...
- Daisy CMS - allowing attributes in the SimpleDocum...
- JSF - ensuring your [xhtml] pages load with a text...
- Eclipse Galileo (3.5): Creating and running a JSF ...
- Using Eclipse Galileo to develop JSF applications ...
- SVN Web view - looking at older revisions
- Notes on setting up mod_proxy on apache 2.2 for pr...
- Addressing stability issues when running Eclipse 3...
- Forcing glassfish 2.1 to start-up with JDK1.6 (OSX...
-
►
April
(6)
- XSLT, text-transform:captialize and Excel workbook...
- Structure for Regular Expressions in Javascript
- SQL Server : Granting EXEC on Stored Procedures
- Eclipse : Save Actions for autoformatting code and...
- Eclipse : Display heap status (like IntelliJ IDEA)...
- Eclipse : Display Java Type Indicator for classes
-
►
June
(10)
0 comments:
Post a Comment