Im using hashmap and arraylist...
How to sort the arraylist ? eg) In hashmap values are in order like one,two,three,four,five
but i stored these values in arraylist the order changed like three,one,five,two,four
In my code groupList,gnamelist and newList are all arraylist...
In print sts PLACES are in correct order but while print on NEWLIST PLACES the order changed
How to sort this in order?
My code
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PLACE, gname);
map.put(TAG_HOTEL,lname);
// adding HashList to ArrayList
groupList.add(map);
gnamelist.add(gname);
System.out.println("PLACES" + gnamelist);
List<String> newList = new ArrayList<String>(new LinkedHashSet<String>(gnamelist));
Collections.sort(newList,Collections.reverseOrder());
System.out.println("NEWLIST PLACES" + newList);
HashSet will store elements in an unordered fashion, and is likely the culprit of your element reordering.
List<String> newList = new ArrayList<String>(new HashSet<String>(gnamelist));
Also consider using LinkedHashMap/LinkedHashSet, which preserves the ordering of elements added to it.
Alternatively try the following:
gnamelist.add(gname);
System.out.println("PLACES" + gnamelist);
List<String> newList = new ArrayList<String>();
newList.addAll(gnamelist);
Try
Collections.sort(newList);
Edit:
If you want to sort in reverse use this
Collections.sort(newList,Collections.reverseOrder());
Important:
if you want to preserve insertion order, you need to use TreeSet instead of HashSet as HashSet doesn't preserve insertion order
Related
How to add some value in ArrayList which is inside of HashMap? My bellow code showing 0 sizes of the hash
val hash= HashMap<String, ArrayList<String> >()
hash["bro"]?.add("Ali Umar")
hash["sis"]?.add("Tamanna")
hash["bro"]?.add("Faruk")
hash["sis"]?.add("Aklima")
hash["bro"]?.add("Ab Siddik")
Log.d("Hash", hash.size.toString())
You have to initialize a List and put the key and that initialized List into the HashMap before you can add any more items to the value of a key. In your example code nothing is put into the HashMap and nothing can be added.
Try it like this (or similar)
fun main() {
// initialize the hashmap
val hash = hashMapOf<String, MutableList<String>>()
// put the keys with empty lists into the hashmap
hash.put("bro", mutableListOf())
hash.put("sis", mutableListOf())
// add items to the value (the list) of existing keys
hash.get("bro")?.add("Ali Umar")
hash.get("sis")?.add("Tamanna")
hash.get("bro")?.add("Faruk")
hash.get("sis")?.add("Aklima")
hash.get("bro")?.add("Ab Siddik")
// print size and content
println("Hash size is ${hash.size.toString()}")
println(hash)
}
In the Kotlin Playground this outputs
Hash size is 2
{sis=[Tamanna, Aklima], bro=[Ali Umar, Faruk, Ab Siddik]}
The problem is that the following instructions are just reading from the hashmap but not inserting anything
hash["bro"]
hash["sis"]
so when you create your hashmap with val hash= HashMap<String, ArrayList<String> >() it is empty and "bro" and "sis" do not exist. so it is null and the add function will not be called because of ?. skips execution if the value is null.
so to add something to bro and sis you first have to put values to your hashmap.
hash.put("bro",ArrayList<String>())
hash.put("sis",ArrayList<String>())
this would change your example as follows
val hash= HashMap<String, ArrayList<String> >()
hash.put("bro",ArrayList<String>())
hash.put("sis",ArrayList<String>())
hash["bro"]?.add("Ali Umar")
hash["sis"]?.add("Tamanna")
hash["bro"]?.add("Faruk")
hash["sis"]?.add("Aklima")
hash["bro"]?.add("Ab Siddik")
Log.d("Hash", hash.size.toString())
I have a hashmap which have same value but different key.I want to sort them how this will possible?
Image of this Hashmap is below
HashMap Image
public static HashMap<String,Integer> entry = new HashMap<>();
Use TreeMap for sorting by key
Use below code for sorting by value:
private static HashMap sortByValues(HashMap map) {
List list = new LinkedList(map.entrySet());
// Defined Custom Comparator here
Collections.sort(list, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());
}
});
// Here I am copying the sorted list in HashMap
// using LinkedHashMap to preserve the insertion order
HashMap sortedHashMap = new LinkedHashMap();
for (Iterator it = list.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
sortedHashMap.put(entry.getKey(), entry.getValue());
}
return sortedHashMap;
}
Please check here for details.
Here some good example for sorting HashMap in Java by Keys and Values.
HashMap is not meant to keep entries in sorted order, but if you have to sort HashMap based upon keys or values, you can do that in Java. Sorting HashMap on keys is quite easy, all you need to do is to create a TreeMap by copying entries from HashMap. TreeMap is an implementation of SortedMap and keeps keys in their natural order or a custom order specified by Comparator provided while creating TreeMap. This means you can process entries of HashMap in a sorted order but you cannot pass a HashMap containing mappings in a specific order, this is just not possible because HashMap doesn't guarantee any ordering. On other hand, sorting HashMap by values is rather complex because there is no direct method to support that operation. You need to write code for that. In order to sort HashMap by values you can first create a Comparator, which can compare two entries based on values. Then get the Set of entries from Map, convert Set to List and use Collections.sort(List) method to sort your list of entries by values by passing your customized value comparator. This is similar of how you sort an ArrayList in Java. Half of the job is done by now. Now create a new LinkedHashMap and add sorted entries into that. Since LinkedHashMap guarantees insertion order of mappings, you will finally have a Map where contents are sorted by values.
Detailed information over here:
https://www.java67.com/2015/01/how-to-sort-hashmap-in-java-based-on.html
i have two ArrayLists:
List<String> names = new ArrayList<String>(10);
List<Drawable> drawables = new ArrayList<Drawable>(10);
which i want to sort alphabetically.
For this i created a TreeMap:
Map<List<String>, List<Drawable>> myMapToSort = new TreeMap<List<String>, List<Drawable>>();
myMapToSort.put(names, drawables);
First two Question
Is the map now sorted in lexicographical order? Or do i Need to do something additional?
After i have sorted them, if they are yet, i want to split them back again to List<String> and List<Drawable>. And i tried like this:
List<String> sortedNames = new ArrayList<String>(myMapToSort.keySet());
Of course it doesn't work because myMapToSort.keySet() Returns a Set and not List.
And List doesn't have an Constructor for a Set.
So how can i accomplish that and what i'm misunderstanding?
Any help is appreciated. Thanks in advance!
I figured it out by my own.
The key was to create a TreeMap with not two list but two single Objects:
Map<String, Drawable> myTreeMap = new TreeMap<String, Drawable>;
Then add the Items from the Arraylists one by one to the Map:
for(int i = 0; i<names.size(); i++) {
myTreeMap.put(names.get(i), drawables.get(i));
}
Now the Map is automatically sorted Lexicographical in relation with the Drawables.
That means Names and Drawables are sorted in lexicographical order.
If you want to retrieve the keys and the values and put them back in seperate ArrayLists simply type:
List <String> mySortedNames = new ArrayList<String>(myTreeMap.keySet());
List <Drawables> mySortedDrawables = new ArrayList<Drawables>(myTreeMap.values());
That's it. ;)
You can use SortedSet (or SortedList) to have sorted elements. The elements are ordered using their natural ordering, or by a Comparator typically provided at sorted set creation time.
For splitting a Map in two lists :
List<String> sortedNames = new ArrayList<String>();
List<Drawable> drawables = new ArrayList<Drawable>();
for (Map.Entry<String, Drawable> entry : map.entrySet())
{
sortedNames.add(entry.getKey()
drawables.add(entry.getValue());
}
I'm trying to implement an expandable listview with data coming from a database. I've already tried having the data added within the codes and it works so I'm now trying to have dynamic data from the database populate the listview.
The data is grouped in two, the main category and the member. For example if the main category is fruit, it's members may include mango, avocado, apples, etc. If animals, it may have horses, eagle, shark. The data always comes in pairs such as Animal, Horses; Animal, Eagle; Fruit, Apples. The expandable listview should appear as:
Animal
-- Horses
-- Eagle
Fruit
-- Apples
My code below can already determine the main group so the headers already display the main groupings of Fruit and Animal. By using
group_member.put(family_name, member_name);
I linked the member to the main category. My problem now is how to code for the iteration to group the members to the main category. So far I've already tried using iterator based on the sample codes given here in stackoverflow and from other sites however only the last elements of each group is display. I've also tried using the for-each loop bur still no success.
String json = jsonParser.makeHttpRequest(URL_COMPONENTS, "POST", params);
JSONArray components = null;
ArrayList<HashMap<String, String>> componentList;
List<String> main_group = new ArrayList<String>();
HashMap<String, String> group_member = new HashMap<String, String>();
try {
components = new JSONArray(json);
if (components != null) {
for (int i = 0; i < components.length(); i++) {
JSONObject c = components.getJSONObject(i);
String family_name = c.getString(TAG_FAMILY_NAME);
String member_name = c.getString(TAG_MEMBER_NAME);
main_group.add(family_name);
group_member.put(family_name, member_name);
if (!listDataHeader.contains(main_group))
listDataHeader.add(main_group);
componentList.add(group_member);
}
}
}
Please help. Thanks in advance!
If you're using HashMap you can't have a key more than once in your list. Each key must be unique.
This could be a solution:
HashMap<String, ArrayList<String>> group_member = new HashMap<String, ArrayList<String>>();
... using the Hashmap as a directory and the key is returning an Arraylist of the family members.
im wondering, how can I sort my arraylist:
its look like this:
ArrayList<HashMap<String, ?>> list = new ArrayList<HashMap<String, ?>>();
temp.put("Position", count);
list.add(temp);
I would sort by Position key.
please try it.
Comparator comparator = Collections.reverseOrder();
Collections.sort(list,comparator);
And also check it.
Sort a Map<Key, Value> by values (Java)
If what you want is to sort the map entries by their keys, you can use a SortedMap (e.g. TreeMap):
List<SortedMap<String, ?>> list = new ArrayList<SortedMap<String, ?>>();