This question already has answers here:
Collections sort(List<T>,Comparator<? super T>) method example [duplicate]
(4 answers)
Closed 9 years ago.
I have an ArrayList defined as so:
ArrayList<HashMap<String, String>> recallList = new ArrayList<HashMap<String, String>>();
Each map only has one element in it company which is the name of a company. My question is how do I alphabetize the ArrayList. I am using this because later down the line (in other views) there will be more elements to the HashMap.
Use the following:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
public class MainClass {
public static void main(String[] args) {
ArrayList<HashMap<String, String>> recallList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> hashMap;
hashMap = new HashMap<String, String>();
hashMap.put("company", "a");
recallList.add(hashMap);
hashMap = new HashMap<String, String>();
hashMap.put("company", "c");
recallList.add(hashMap);
hashMap = new HashMap<String, String>();
hashMap.put("company", "b");
recallList.add(hashMap);
System.out.println(recallList);
Collections.sort(recallList, new Comparator<HashMap<String, String>>() {
#Override
public int compare(HashMap<String, String> hashMap1, HashMap<String, String> hashMap2) {
return hashMap1.get("company").compareTo(hashMap2.get("company"));
}
});
System.out.println(recallList);
}
}
The first and second output are:
[{company=a}, {company=c}, {company=b}]
[{company=a}, {company=b}, {company=c}]
You can use Collections.sort() to sort it in lexicographically order but you have make the object comparable by using Comparator
class CmpHashMap implements Comparator<HashMap<String,String>>
{
public int compare(HashMap<String,String> h1,HashMap<String,String> h2)//assuming second String as company name and key as "key"
{
return h1.get("key").compareTo(h2.get("key"));
}
}
then use collections
Collections.sort(recalllist,new CmpHashMap());
Related
Trying to sort HashMap of <String,Double> without using treeMap or other method. Need the code to pass a hashMap and return a sorted hashMap in the fastest time. What am I doing wrong with the string Comparator. Please look and advise. Thank you very much!!!
/// Here's the main
package Sort_String_Double_without_TreeMap;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) throws InterruptedException {
Map<String, Double> outGoing = new HashMap<>();
outGoing.put("J", -5.0);
outGoing.put("X", 0.7);
outGoing.put("C", 0.0);
outGoing.put("D", 80.0);
outGoing.put("A", 80.0);
System.out.println("---UNSORTED---");
System.out.println(outGoing);
TimeUnit.SECONDS.sleep(1);
Helper_SorterClass sorter = new Helper_SorterClass ();
System.out.println("---SORTED---");
System.out.println();
System.out.println("SIZE= " + sorter.SortHashMapKey(outGoing).size());
System.out.println(sorter.SortHashMapKey(outGoing));
}
}
And Here's the other class...
/// Here's the helper class
package Sort_String_Double_without_TreeMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Helper_SorterClass {
public Map<String, Double> SortHashMapKey(Map<String, Double> unsortedMap) {
List<String> list = new ArrayList(unsortedMap.keySet());
Collections.sort(list, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return String.valueOf(o1).compareTo(String.valueOf(o2));
}
});
Map<String, Double> sortedMap = new HashMap<>();
for (String keys : list) {
sortedMap.put(keys, unsortedMap.get(keys));
}
return sortedMap;
}
}
Unfortunately getting wrong output.
run:
---UNSORTED---
{A=80.0, C=0.0, D=80.0, X=0.7, J=-5.0}
---SORTED---
SIZE= 5
{A=80.0, C=0.0, D=80.0, X=0.7, J=-5.0}
BUILD SUCCESSFUL (total time: 1 second)
Map<String, Double> sortedMap = new HashMap<>();
for (String keys : list) {
sortedMap.put(keys, unsortedMap.get(keys));
}
you should use LinkedHashMap instead of HashMap as below:
Map<String, Double> sortedMap = new LinkedHashMap<>();
for (String keys : list) {
sortedMap.put(keys, unsortedMap.get(keys));
}
HashMap doesn't maintain insertion order. So once you put the entries in a new HashMap() after comparing, it will again give unsorted result when you iterate over the new map. But if you use a LinkedHashMap, it will maintain insertion order while iterating.
This question already has answers here:
Sort a Map<Key, Value> by values
(64 answers)
How can I sort Map values by key in Java?
(17 answers)
Closed 3 years ago.
Sort a Map by Key or by value in java
Input Map 1-eee 4-ddd 5-ccc 0-bbb 3-aaa
1st Output Map(By-Key): 0-bbb 1-eee 3-aaa 4-ddd 5-ccc
2nd Output Map(By-Value): 3-aaa 0-bbb 5-ccc 4-ddd 1-eee
This code will first sort the map by Key and then by value.
Just write a main method and call this method as follow:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class SortMapByKeyAndValue
{
public static void main(String[] args)
{
aMapSortProgramByKeyAndValue();
}
private static void aMapSortProgramByKeyAndValue()
{
Map<String, Integer> myMap = new HashMap<String, Integer>();
// putting values in the Map
myMap.put("Jayant", 80);
myMap.put("Abhishek", 90);
myMap.put("Anushka", 80);
myMap.put("Amit", 75);
myMap.put("Spandan", 50);
myMap.put("Hari", 55);
myMap.put("Keshav", 60);
System.out.println("Map data without Sort :-");
for (Entry<String, Integer> myEntryMapData : myMap.entrySet())
{
System.out.println("The Map data is Key: " + myEntryMapData.getKey() + " Value: "
+ myEntryMapData.getValue());
}
List<Entry<String, Integer>> myMapDataAsList = new ArrayList<Map.Entry<String, Integer>>();
myMapDataAsList.addAll(myMap.entrySet());
System.out.println("Map data Stored in List, The whole List is : " + myMapDataAsList);
Iterator<Entry<String, Integer>> myListIterator = myMapDataAsList.iterator();
System.out.println("Map data Stored in List, Print through iterator :-");
for (; myListIterator.hasNext();)
{
Entry<String, Integer> myListData = myListIterator.next();
System.out.println("The List data is Key: " + myListData.getKey() + " Value: " + myListData.getValue());
}
Collections.sort(myMapDataAsList, new Comparator<Entry<String, Integer>>()
{
#Override
public int compare(Entry<String, Integer> dataOne, Entry<String, Integer> dataTwo)
{
return dataOne.getKey().compareTo(dataTwo.getKey());
}
});
System.out.println("After Sort by the Key the Map data is : ");
myListIterator = myMapDataAsList.iterator();
for (; myListIterator.hasNext();)
{
Entry<String, Integer> myListData = myListIterator.next();
System.out.println("The List data is Key: " + myListData.getKey() + " Value: " + myListData.getValue());
}
Collections.sort(myMapDataAsList, new Comparator<Entry<String, Integer>>()
{
#Override
public int compare(Entry<String, Integer> dataOne, Entry<String, Integer> dataTwo)
{
return dataOne.getValue().compareTo(dataTwo.getValue());
}
});
System.out.println("After Sort by the vale the Map data is : ");
myListIterator = myMapDataAsList.iterator();
for (; myListIterator.hasNext();)
{
Entry<String, Integer> myListData = myListIterator.next();
System.out.println("The List data is Key: " + myListData.getKey() + " Value: " + myListData.getValue());
}
}
}
import java.util.Collections;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class MapSortUtil
{
public static Map<String, String> sortMapByKey(Map<String, String> anUnSortedMap)
{
List<Entry<String, String>> myListOfEntrySet = getListOfEntrySetFromMap(anUnSortedMap);
/* Sort the list of entry-set in ascending order. */
Collections.sort(myListOfEntrySet, new MapComparatorToSortByKey());
/* Generating new Map from Sorted Entry List. */
Map<String, String> mySortedMap = getSortedMapFromSortedEntry(myListOfEntrySet);
return mySortedMap;
}
public static Map<String, String> sortMapByValue(Map<String, String> anUnSortedMap)
{
List<Entry<String, String>> myListOfEntrySet = getListOfEntrySetFromMap(anUnSortedMap);
/* Sort the list of entry-set in ascending order. */
Collections.sort(myListOfEntrySet, new MapComparatorToSortByValue());
/* Generating new Map from Sorted Entry List. */
Map<String, String> mySortedMap = getSortedMapFromSortedEntry(myListOfEntrySet);
return mySortedMap;
}
private static List<Entry<String, String>> getListOfEntrySetFromMap(Map<String, String> anUnSortedMap)
{
/* Getting Entry Set from the Map. */
Set<Entry<String, String>> myEntrySetOfMap = anUnSortedMap.entrySet();
/* Creating List of Entry Set. */
List<Entry<String, String>> myListOfEntrySet = new LinkedList<Map.Entry<String, String>>(myEntrySetOfMap);
return myListOfEntrySet;
}
private static Map<String, String> getSortedMapFromSortedEntry(List<Entry<String, String>> myListOfEntrySetOfMap)
{
/* Add Sorted list in new LinkedHashMap one-by-one. */
Map<String, String> mySortedLinkedHashMap = new LinkedHashMap<String, String>();
for (Entry<String, String> myOneByOneData : myListOfEntrySetOfMap)
{
mySortedLinkedHashMap.put(myOneByOneData.getKey(), myOneByOneData.getValue());
}
return mySortedLinkedHashMap;
}
}
class MapComparatorToSortByValue implements Comparator<Entry<String, String>>
{
#Override
public int compare(Entry<String, String> aMap1, Entry<String, String> aMap2)
{
return aMap1.getValue().compareTo(aMap2.getValue());
}
}
class MapComparatorToSortByKey implements Comparator<Entry<String, String>>
{
#Override
public int compare(Entry<String, String> aMap1, Entry<String, String> aMap2)
{
return aMap1.getKey().compareTo(aMap2.getKey());
}
}
This doesn't compile:
Map<String, Object> map = new HashMap<String, Object>();
HashMultiset<Map<String, Object>> n1Properties = HashMultiset.create(map);
None of the overloaded create methods accepts a Map. But you can use the addAll method to add the Map converted to a Collection.
import com.google.common.collect.HashMultiset;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class SO {
public static void main(String args[]) {
Map<String, Object> map = new HashMap<>();
map.put("foo", "FOO");
map.put("bar", "BAR");
HashMultiset<Map<String, Object>> n1Properties = HashMultiset.create();
n1Properties.addAll(Collections.singleton(map));
System.out.println(n1Properties);
}
}
Output:
[{bar=BAR, foo=FOO}]
I have a List of objects. Some objects are Map<String, String> and others are Map<String, List<String>> types. I need to group those in to different lists.
Please tell me If there any methods to handle these challenge.
This looked like a fun code challenge. I wrote a small java class demonstrating how you can use 'instanceof' operator to split out these values into separate collections.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class Scratch {
public static void main(String[] args) {
// test data
List<Map<String, ?>> mixed = new ArrayList<>();
Map<String, String> strings = new HashMap<>();
strings.put("x", "y");
Map<String, List<String>> lists = new HashMap<>();
List<String> list = new ArrayList<>();
list.add("z");
lists.put("w", list);
mixed.add(strings);
mixed.add(lists);
// split out data
Map<String, String> onlyStrings = new HashMap<>();
Map<String, List<String>> onlyLists = new HashMap<>();
for (Map<String, ?> item : mixed) {
for (Map.Entry<String, ?> entry : item.entrySet()) {
Object value = entry.getValue();
if (value instanceof String) {
onlyStrings.put(entry.getKey(), (String)entry.getValue());
} else if (value instanceof List) {
onlyLists.put(entry.getKey(), (List<String>)entry.getValue());
}
}
}
// print out
System.out.println("---Strings---");
for (Map.Entry<String, String> entry : onlyStrings.entrySet()) {
System.out.println(entry);
}
System.out.println("---Lists---");
for (Map.Entry<String, List<String>> entry : onlyLists.entrySet()) {
System.out.println(entry);
}
}
}
Output
---Strings---
x=y
---Lists---
w=[z]
Hope it helps and is what you are after
I'm having trouble applying sorting mechanism through my application.
Reason was sometimes sort are not accurate and also the comparator thing in java still not clear for me, but i have used sort here and there.
Now, current problem is as follows.
I have
HashMap<String, ModelX.ContactModel> unsortedModelContacts =
new HashMap<String,ModelX.ContactModel>(contacts.size());
After that I fached
contactlist and using for loop I have put the values as follows:
unsortedModelContacts.put(stringvalue, modelContact);
//object having name , and other details
How can I sort the unsortedModelContacts sorting modelContact.getName property?
If your map's key is different from the name field then you can consider using this approach. Writing a separate comparator
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import sample.ModelX.ContactModel;
public class SortMapSample {
public static void main(String[] args) throws Exception {
Map<String, ModelX.ContactModel> unsortedModelContacts = new HashMap<String,ModelX.ContactModel>(10);
unsortedModelContacts.put("1", new ModelX.ContactModel("James"));
unsortedModelContacts.put("2", new ModelX.ContactModel("Mary"));
unsortedModelContacts.put("3", new ModelX.ContactModel("John"));
unsortedModelContacts.put("4", new ModelX.ContactModel("Amanda"));
unsortedModelContacts.put("5", new ModelX.ContactModel("Charles"));
System.out.println(sortMap(unsortedModelContacts));
}
private static Map<String, ModelX.ContactModel> sortMap(
Map<String, ModelX.ContactModel> unsortedMap) {
List<Entry<String, ModelX.ContactModel>> list = new LinkedList<Entry<String, ModelX.ContactModel>>(
unsortedMap.entrySet());
Collections.sort(list,
new Comparator<Entry<String, ModelX.ContactModel>>() {
#Override
public int compare(Entry<String, ContactModel> o1,
Entry<String, ContactModel> o2) {
return o1.getValue().getName().compareTo(o2.getValue().getName());
}
});
Map<String, ModelX.ContactModel> sortedMap = new LinkedHashMap<String, ModelX.ContactModel>();
for(Entry<String, ModelX.ContactModel> item : list){
sortedMap.put(item.getKey(), item.getValue());
}
return sortedMap;
}
}
SortedMap<String,ModelX.ContactModel> sortedModelContacts = new TreeMap<>();
for( ModelX.ContactModel modelContact: contactlist ){ // same list as before
sortedModelContacts.put( modelContact.getName(), modelContact);
}
You can now access entries of this map in sort order of the name property.
Note: this assumes that names are unique. If this isn't true, you'll have to use a multimap or
Map<String,ModelX.Set<ContactModel>>
and modify the put and other accesses accordingly.