I currently have a setup where the data structure is an ArrayList with each key containing a HashMap for each key in ArrayList. What I'm trying to do is be able to sort by key or keys within the HashMap itself. In my research, most advice seems to be to use Collections.sort(ArrayList, comparatorFunction()) and then build a custom Comparatorfunction to do the sorting, but as a complete noob as to how to build a Comparator...I don't even know where to start, much less build one that' I'm sure is not a simple setup. Anyone happen to know of some resources that would be useful to address this kind of functionality?
EDIT: Sorry some sample structure would be helpful.
if you called arrayList.get(0) and did a System.out.println on it, it would return say {town=Toronto, population=2,500,000, age=147}, what I'm trying to do is have it so I could say order the ArrayList by say population, and then age for example.
Usually in situations like this the job of the Comparator is to simple return the value of a compare from something else. For example, here is a Comparator that will alphabetize Fonts:
class FontAlphabetizer
implements Comparator<Font> {
#Override
public int compare(Font font1, Font font2) {
return font1.getName().compareTo(font2.getName());
}
}
That's actually pretty simple: getName returns a String and all we do is return the value of String's compareTo method.
Here it seems like what you have is an ArrayList<Map> and you want to sort the ArrayList based on a chosen value from the Map. So what you need is a Comparator<Map>. And you need to give the Comparator the key for the corresponding value that you want to sort by. This can be expressed generically like the following:
class MapValueComparator<K, V extends Comparable<V>>
implements Comparator<Map<K, V>> {
final K key;
MapValueComparator(K key) {
this.key = key;
}
#Override
public int compare(Map<K, V> map1, Map<K, V> map2) {
return map1.get(key).compareTo(map2.get(key));
}
}
That is a Comparator that compares Maps and it's specified in the declaration there that the Map's values must also be Comparable. It compares based on the value retrieved from the given key.
So for example if we have an ArrayList<Map<String, String>>, we can sort by the value from "town" like this:
static void sortByTown(List<Map<String, String>> list) {
Collections.sort(list, new MapValueComparator<String, String>("town"));
}
The hiccup is that you say you have town=Toronto, population=2,500,000 which indicates that the population you want to sort by is a String (since presumably it's in the same map as Toronto). Comparing population as String probably isn't desired because it will sort lexicographically (50 comes after 2,500,000 because 5 comes after 2). In that case the generic version might not work because you need to take an extra step of converting the value to a number.
class PopulationComparator
implements Comparator<Map<String, String>> {
#Override
public int compare(Map<String, String> map1, Map<String, String> map2) {
final Long pop1 = Long.valueOf(map1.get("population"));
final Long pop2 = Long.valueOf(map2.get("population"));
return pop1.compareTo(pop2);
}
}
(And as a side note if your population contains commas you'd need to format that before parsing it to a number. You can use replaceAll("\\D", "") to remove all non digits from a String.)
This is also a case where it could be advantageous to create a class for this instead of using a Map. Then you could have the numerical fields be number types. If you had a class, the comparison would be mostly the same though: just returning a comparison of a chosen field.
Custom Comparator can be used to define the way the objects of your class can be compared. It has the following Syntax :
public class CustomComparator implements Comparator<MyObjectType>
{
public int compare(MyObjectType ob1 , MyObjectType ob2)
{
//code to compare the 2 objects
}
}
Refer to the following link for information on creating a Comparator class for custom sorting of elements in collection : link
Here is what you are looking for:
final List<Map<String, Object>> towns = new ArrayList<Map<String, Object>>();
final Map<String, Object> toronto = new HashMap<String, Object>();
toronto.put("town", "Toronto");
toronto.put("population", 2500000);
toronto.put("age", 147);
towns.add(toronto);
final Map<String, Object> ottawa = new HashMap<String, Object>();
ottawa.put("town", "Ottawa");
ottawa.put("population", 883000);
ottawa.put("age", 159);
towns.add(ottawa);
final Map<String, Object> montreal = new HashMap<String, Object>();
montreal.put("town", "Montreal");
montreal.put("population", 1600000);
montreal.put("age", 372);
towns.add(montreal);
final Map<String, Object> quebec = new HashMap<String, Object>();
quebec.put("town", "Quebec City");
quebec.put("population", 600000);
quebec.put("age", 406);
towns.add(quebec);
final Map<String, Object> vancouver = new HashMap<String, Object>();
vancouver.put("town", "Vancouver");
vancouver.put("population", 600000);
vancouver.put("age", 128);
towns.add(vancouver);
Collections.sort(towns, new Comparator<Map<String, Object>>() {
#Override
public int compare(final Map<String, Object> o1, final Map<String, Object> o2) {
if (o1.get("population") instanceof Integer && o2.get("population") instanceof Integer && !((Integer)o1.get("population")).equals((Integer)o2.get("population"))) {
return ((Integer)o1.get("population")).compareTo((Integer)o2.get("population"));
}
if (o1.get("age") instanceof Integer && o2.get("age") instanceof Integer) {
return ((Integer)o1.get("age")).compareTo((Integer)o2.get("age"));
}
// Default if there is no population/no age, shouldn't happen.
// TODO : do something else.
return o1.toString().compareTo(o2.toString());
}
});
for (final Map<String, Object> town: towns) {
System.out.println(town.get("population")+"\t"+town.get("age")+"\t"+town.get("town"));
}
The first part of the code is just to create the ArrayList according to what you said you have, then we use a custom Comparator to sort the List, and print the result.
Here is the output:
600000 128 Vancouver
600000 406 Quebec City
883000 159 Ottawa
1600000 372 Montreal
2500000 147 Toronto
As you can see, it's sorted by population, then by age.
But, maybe the best solution would be to create an object Town, with three fields (name, population and age), and use this object instead of the HashMaps.
Related
In a Java class I have a method to reOrder an existing HashMap by date. The HashMap is of a type <String, Object> where the Object contains a field called expPayDate and the key string is a sequential number turned into a string.. So I need to loop through the items in the sourceMap and find the item with the newest date then copy it to a tempMap in the correct order. My issue is what is the best way to determine the item with the newest date.
Your best bet will be to use a SortedMap with the Comparator interface.
Here is an example:
public SortedMap<String, Object> getSortedMap(Map<String, Object> originalMap) {
SortedMap<String, Object> tmpMap = new TreeMap<String, Object>(new Comparator<String>(){
#Override
public int compare(String key1, String key2) {
//logic for comparing dates
}
});
tmpMap.putAll(originalMap);
return tmpMap;
}
Use a TreeMap instead of HashMap. it will be sorted automatically on insertion.
Map< Date, Object> m = new TreeMap< Date, Object>();
Alternatively, if you have an existing HashMap and want to create a TreeMap based on it, pass it to the constructor:
Map< Date, Object> sortedMap = new TreeMap< Date, Object>(m);
Hope it will help you.
For simplicity I am assuming that type of your map is something more like Map<String, MyClass> map where MyClass has method like getDate() which returns expPayDate.
My issue is what is the best way to determine the item with the newest date.
If you want to find single map entry which value contains max date you don't need to sort entire map which at best would give you O(n*logn). What you need is simple iteration of all elements in map and comparing them with current max, which will be O(n) operation.
You can use stream() (functionality added in Java 8) and its max method. This method needs Comparator and you can easily create one by using comparing method and passing lambda expression which will return value which should be used when comparing.
So your code can look like
//import java.util.Map.Entry;
Optional<Entry<String, MyClass>> max = map.entrySet().stream()
.max(Comparator.comparing(e -> e.getValue().getDate()));
Entry<String, MyClass> entry = max.get();
MyClass maxMC = entry.getValue();
If you can't use Java 8 you can write your own method which will iterate over elements and find max. Such method can look like
public static <T> T max(Iterable<T> iterable, Comparator<T> comp) {
Iterator<T> it = iterable.iterator();
T max = null;
if (it.hasNext()) {
max = it.next();
}
while (it.hasNext()) {
T tmp = it.next();
if (comp.compare(max, tmp) < 0)
max = tmp;
}
return max;
}
and you can use it like
Comparator<Entry<String, MyClass>> myComparator = new Comparator<Entry<String, MyClass>>() {
#Override
public int compare(Entry<String, MyClass> o1, Entry<String, MyClass> o2) {
return o1.getValue().getDate().compareTo(o2.getValue().getDate());
}
};
Entry<String, MyClass> maxEntry = max(map.entrySet(), myComparator);
MyClass max = maxEntry.getValue();
Get all Entries by calling entrySet() method of Map
Create a custom Comparator to sort entries based upon values
Convert Entry set to List
Sort Entry list by using Collections.sort() method by passing your value comparator
Create a LinkedHashMap by adding entries in sorted order.
Look at example code # Sort HasMap by value
If you just need the minimum or maximum date, a simple for each loop might be sufficient:
Date maxDate = null;
for (Entry<String, Object> item: hashMap.entrySet())
if (maxDate == null || maxDate before((Date)item.getValue()))
maxDate = (Date)item.getValue();
This way complexity is only O(n) and insert and delete operations are cheaper than using a sortedMap. Anyway, I think patstuart's suggestion (using a sortedMap) is more elegant.
The correct solution depends on your performance constraints.
If your issue is just finding the item with the newest date, then if O(n) performance is OK you can do a scan of the values() in your HashMap and find the minimum that way.
It depends on how often you need to do this relative to other access on the data structure. It would be perfectly reasonable to use a SortedMap or use a secondary data structure such as a PriorityQueue (acting as a heap on the date), depending on your access patterns for this data structure.
Can you guide me how can I sort Array List having Hash Map alphabatically?
JSONArray jArr2 = new JSONArray(jsonString2);
for(int i=0;i<jArr2.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
map.put("titleName",jArr2.getJSONObject(i).getString("titleName"))
programList.add(map);
}
Implement a Comparator<HashMap<String, String>> which just extracts the value assocated with the value key, then use Collections.sort method to sort your arraylist.
For e.g.:
class MyComparator implements Comparator<Map<String, String>>{
private final String key;
public MyComparator(String key)
{
this.key = key;
}
public int compare(Map<String, String> first,
Map<String, String> second)
{
// TODO: Null checking, both for maps and values
String firstValue = first.get(key);
String secondValue = second.get(key);
return firstValue.compareTo(secondValue);
}
}
Looking at your example, I don't think you need a Map to be involved at all. What you have is a list of Maps, where every Map only has one key, which is "titleName". Why not just have a list of titlenames? Then your code would look like this:
JSONArray jArr2 = new JSONArray(jsonString2);
List<String> titleNames = new ArrayList<>();
for (int i = 0; i < jArr2.length(); i++) {
titleNames.add(jArr2.getJSONObject(i).getString("titleName"))
}
You know that the list only contains titleNames, you don't need to complicate the data structure with Maps!
Then you can sort the list simply by using
Collections.sort(titleNames);
Note that this will work while the other answers that suggests Collections.sort() on the list of maps will not work. This is because titleNamees is a List of Strings, which implement Comparable (ie the sort() method knows how to order them with respect to each other), while Map does not implement comparable (as there are multiple ways to order Maps - number of entries, total number of bytes, etc).
Yes you can use Collections.sort(); with a custom comparator. Here is the doc.
Collections.sort(YOUR_ARRAY_LIST, new YourCustomComparator());
And this should be the class you must have
class YourCustomComparator implements Comparator<HashMap<String, String>> {
#Override
public int compare(HashMap<String, String> lhs, HashMap<String, String> rhs) {
// check here your objects. lhs and rhs. compare them as you want
// return 1 if lhs is greater than rhs
// return 0 if ther are same
// return -1 otherwise
}
}
I have a map like this
Map map=new HashMap();//HashMap key random order.
map.put("a",10);
map.put("a",20);
map.put("a",30);
map.put("b",10);
System.out.println("There are "+map.size()+" elements in the map.");
System.out.println("Content of Map are...");
Set s=map.entrySet();
Iterator itr=s.iterator();
while(itr.hasNext())
{
Map.Entry m=(Map.Entry)itr.next();
System.out.println(m.getKey()+"\t"+m.getValue()+"\t"+ m.hashCode());
}
Output of the above program is
There are 2 elements in the map.
Content of Map are...
b 10 104
a 30 127
Now I want that key a should have multiple values like
a 10
a 20
a 30
So that I should get all the values associated by a. Please advise how can I achieve that same thing. By nesting of collections, I want key 'a' to have all the three values.
Have you checked out Guava Multimaps ?
A collection similar to a Map, but which may associate multiple values
with a single key. If you call put(K, V) twice, with the same key but
different values, the multimap contains mappings from the key to both
values.
If you really want to use standard collections (as suggested below), you'll have to store a collection per key e.g.
map = new HashMap<String, Collection<Integer>>();
Note that the first time you enter a new key, you'll have to create the new collection (List, Set etc.) before adding the first value.
To implement what you want using the Java standard library, I would use a map like this:
Map<String, Collection<Integer>> multiValueMap = new HashMap<String, Collection<Integer>>();
Then you can add values:
multiValueMap.put("a", new ArrayList<Integer>());
multiValueMap.get("a").add(new Integer(10));
multiValueMap.get("a").add(new Integer(20));
multiValueMap.get("a").add(new Integer(30));
If this results uncomfortable for you, consider wrapping this behaviour in a dedicated Class, or using a third-party solution, as others have suggested here (Guava Multimap).
You shouldn't ignore the generic parameters. What you have is
Map<String, Integer> map = new HashMap<>();
if you want to code the solution yourself, you need
Map<String, List<Integer>> map = new HashMap<>();
Anyhow, the preffered way is to use a Guava Multimap
Put an ArrayList instance in the value part.
void addValue(Map map, Object key, Object value) {
Object obj = map.get(key);
List list;
if (obj == null) {
list = new ArrayList<Object>();
} else {
list = ((ArrayList) obj);
}
list.add(value);
map.put(key, list);
}
For More Info check this.
Use Map with value type as list of values..For example, in your map, while adding an entry, you will put key as "a" and you will have to add it's value as a list of Integer , having all the required values, like 1,2,3,4.
For a Map with entries with same key, has no sense to use get() .But as long as you use iterator() or entrySet() this should work:
class HashMap<String, String> {
Set<Entry<String, String>> entries;
#Override
public Set<Entry<String, String>> entrySet() {
return entries;
}
#Override
public int size() {
return entries.size();
}
public String put(String key, String value) {
if (entries == null) {
entries = new AbstractSet<Entry<String, String>>() {
ArrayList<Entry<String, String>> list = new ArrayList<>();
#Override
public Iterator<Entry<String, String>> iterator() {
return list.iterator();
}
#Override
public int size() {
return list.size();
}
#Override
public boolean add(Entry<String, String> stringStringEntry) {
return list.add(stringStringEntry);
}
};
}
StatusHandler.MyEntry entry = new StatusHandler.MyEntry();
entry.setKey(key);
entry.setValue(value);
entries.add(entry);
return value;
}
};
TL;DR So, what is it useful for? That comes from a hack to redmine-java-api to accept complex queries based on form params:
https://stackoverflow.com/a/18358659/848072
https://github.com/albfan/RedmineJavaCLI/commit/2bc51901f2f8252525a2d2258593082979ba7122
I have an hashable that contains a string key , and a class object value:
Hashtable<String,myclass>m_class_table = new Hashtable<String,myclass>();
inside 'myclass' I have a String field value,
I need to sort my hashtable according to this string value.
I can't just sort it by the hashtable values beacuse it is an object..
How can this be done?
Thank's In Advance.
I need to sort my hashtable according to this string value.
A hashtable is not a sorted data structure.
You can use some SortedMap, such as a TreeMap but those data structures sorts on the keys, so that will only work if the key equals the string-field of the object pointed to.
I can't just sort it by the hashtable values beacuse it is an object..
You need to provide a Comparator<myclass>, or, let myclass implement the Comparable interface.
Depending on how you iterate over the hash-table, you could perhaps do like this:
List<myclass> myObjects = new ArrayList<myclass>(m_class_table.values());
Collections.sort(myObjects, new Comparator<myclass>() {
#Override
public int compare(myclass o1, myclass o2) {
o1.stringField.compareTo(o2.stringField);
}
});
and then iterate over the myObjects list. (Elements in a List are ordered.)
A slight variation on aioobe's answer: I'd create a List of the Map entries and sort that list. That way you still have access to the complete map entries.
Map<String, MyClass> map = new HashMap<String, MyClass>();
// add some entries
List<Entry<String,MyClass>> entryList =
new ArrayList<Entry<String,MyClass>>(map.entrySet());
Collections.sort(entryList, new Comparator<Entry<String,MyClass>>() {
public int compare(
Entry<String, MyClass> first, Entry<String, MyClass> second) {
return first.getValue().getFoo()
.compareTo(second.getValue().getFoo());
}
});
I'm looking for a class in java that has key-value association, but without using hashes. Here is what I'm currently doing:
Add values to a Hashtable.
Get an iterator for the Hashtable.entrySet().
Iterate through all values and:
Get a Map.Entry for the iterator.
Create an object of type Module (a custom class) based on the value.
Add the class to a JPanel.
Show the panel.
The problem with this is that I do not have control over the order that I get the values back, so I cannot display the values in the a given order (without hard-coding the order).
I would use an ArrayList or Vector for this, but later in the code I need to grab the Module object for a given Key, which I can't do with an ArrayList or Vector.
Does anyone know of a free/open-source Java class that will do this, or a way to get values out of a Hashtable based on when they were added?
Thanks!
I suggest a LinkedHashMap or a TreeMap. A LinkedHashMap keeps the keys in the order they were inserted, while a TreeMap is kept sorted via a Comparator or the natural Comparable ordering of the keys.
Since it doesn't have to keep the elements sorted, LinkedHashMap should be faster for most cases; TreeMap has O(log n) performance for containsKey, get, put, and remove, according to the Javadocs, while LinkedHashMap is O(1) for each.
If your API that only expects a predictable sort order, as opposed to a specific sort order, consider using the interfaces these two classes implement, NavigableMap or SortedMap. This will allow you not to leak specific implementations into your API and switch to either of those specific classes or a completely different implementation at will afterwards.
LinkedHashMap will return the elements in the order they were inserted into the map when you iterate over the keySet(), entrySet() or values() of the map.
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("id", "1");
map.put("name", "rohan");
map.put("age", "26");
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
This will print the elements in the order they were put into the map:
id = 1
name = rohan
age = 26
If an immutable map fits your needs then there is a library by google called guava (see also guava questions)
Guava provides an ImmutableMap with reliable user-specified iteration order. This ImmutableMap has O(1) performance for containsKey, get. Obviously put and remove are not supported.
ImmutableMap objects are constructed by using either the elegant static convenience methods of() and copyOf() or a Builder object.
You can use LinkedHashMap to main insertion order in Map
The important points about Java LinkedHashMap class are:
It contains only unique elements.
A LinkedHashMap contains values based on the key.
It may have one null key and multiple null values.
It is same as HashMap instead maintains insertion order
public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>
But if you want sort values in map using User-defined object or any primitive data type key then you should use TreeMap For more information, refer this link
You can maintain a Map (for fast lookup) and List (for order) but a LinkedHashMap may be the simplest. You can also try a SortedMap e.g. TreeMap, which an have any order you specify.
Either You can use LinkedHashMap<K, V> or you can implement you own CustomMap which maintains insertion order.
You can use the Following CustomHashMap with the following features:
Insertion order is maintained, by using LinkedHashMap internally.
Keys with null or empty strings are not allowed.
Once key with value is created, we are not overriding its value.
HashMap vs LinkedHashMap vs CustomHashMap
interface CustomMap<K, V> extends Map<K, V> {
public boolean insertionRule(K key, V value);
}
#SuppressWarnings({ "rawtypes", "unchecked" })
public class CustomHashMap<K, V> implements CustomMap<K, V> {
private Map<K, V> entryMap;
// SET: Adds the specified element to this set if it is not already present.
private Set<K> entrySet;
public CustomHashMap() {
super();
entryMap = new LinkedHashMap<K, V>();
entrySet = new HashSet();
}
#Override
public boolean insertionRule(K key, V value) {
// KEY as null and EMPTY String is not allowed.
if (key == null || (key instanceof String && ((String) key).trim().equals("") ) ) {
return false;
}
// If key already available then, we are not overriding its value.
if (entrySet.contains(key)) { // Then override its value, but we are not allowing
return false;
} else { // Add the entry
entrySet.add(key);
entryMap.put(key, value);
return true;
}
}
public V put(K key, V value) {
V oldValue = entryMap.get(key);
insertionRule(key, value);
return oldValue;
}
public void putAll(Map<? extends K, ? extends V> t) {
for (Iterator i = t.keySet().iterator(); i.hasNext();) {
K key = (K) i.next();
insertionRule(key, t.get(key));
}
}
public void clear() {
entryMap.clear();
entrySet.clear();
}
public boolean containsKey(Object key) {
return entryMap.containsKey(key);
}
public boolean containsValue(Object value) {
return entryMap.containsValue(value);
}
public Set entrySet() {
return entryMap.entrySet();
}
public boolean equals(Object o) {
return entryMap.equals(o);
}
public V get(Object key) {
return entryMap.get(key);
}
public int hashCode() {
return entryMap.hashCode();
}
public boolean isEmpty() {
return entryMap.isEmpty();
}
public Set keySet() {
return entrySet;
}
public V remove(Object key) {
entrySet.remove(key);
return entryMap.remove(key);
}
public int size() {
return entryMap.size();
}
public Collection values() {
return entryMap.values();
}
}
Usage of CustomHashMap:
public static void main(String[] args) {
System.out.println("== LinkedHashMap ==");
Map<Object, String> map2 = new LinkedHashMap<Object, String>();
addData(map2);
System.out.println("== CustomHashMap ==");
Map<Object, String> map = new CustomHashMap<Object, String>();
addData(map);
}
public static void addData(Map<Object, String> map) {
map.put(null, "1");
map.put("name", "Yash");
map.put("1", "1 - Str");
map.put("1", "2 - Str"); // Overriding value
map.put("", "1"); // Empty String
map.put(" ", "1"); // Empty String
map.put(1, "Int");
map.put(null, "2"); // Null
for (Map.Entry<Object, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
}
O/P:
== LinkedHashMap == | == CustomHashMap ==
null = 2 | name = Yash
name = Yash | 1 = 1 - Str
1 = 2 - Str | 1 = Int
= 1 |
= 1 |
1 = Int |
If you know the KEY's are fixed then you can use EnumMap. Get the values form Properties/XML files
EX:
enum ORACLE {
IP, URL, USER_NAME, PASSWORD, DB_Name;
}
EnumMap<ORACLE, String> props = new EnumMap<ORACLE, String>(ORACLE.class);
props.put(ORACLE.IP, "127.0.0.1");
props.put(ORACLE.URL, "...");
props.put(ORACLE.USER_NAME, "Scott");
props.put(ORACLE.PASSWORD, "Tiget");
props.put(ORACLE.DB_Name, "MyDB");
I don't know if it is opensource, but after a little googling, I found this implementation of Map using ArrayList. It seems to be pre-1.5 Java, so you might want to genericize it, which should be easy. Note that this implementation has O(N) access, but this shouldn't be a problem if you don't add hundreds of widgets to your JPanel, which you shouldn't anyway.
Whenever i need to maintain the natural order of things that are known ahead of time, i use a EnumMap
the keys will be enums and you can insert in any order you want but when you iterate it will iterate in the enum order (the natural order).
Also when using EnumMap there should be no collisions which can be more efficient.
I really find that using enumMap makes for clean readable code.
Here is an example