I have Map<String, List<String>> map now, putting two values inside Map, now when read keyset from map gives in different sequence in different device.
private Map<String, List<String>> map = new HashMap<>();
map.put("First", new ArrayList<String>());
map.put("Second", new ArrayList<String>());
Now, Read keys from this map.
Set<String> keys = map.keySet();
for (int i = 0; i < map.size(); i++) {
Log.d("key", keys.toArray()[i].toString());
}
OUTPUT IN OREO 8.0
D/Key : First
D/Key : Second
OUTPUT in BELOW 8.0
D/Key : Second
D/Key : First
I got a solution until we defined Set as SortedSet ,we getting key sequence in different order.
SortedSet<String> keys = new TreeSet<>(map.keySet());
for (int i = 0; i < map.size(); i++) {
Log.d("key", keys.toArray()[i].toString());
}
You're using the HashMap as the data structure. As in HashMap, the order of insertion is not maintained thus you're getting a random order of the keys. If you want to maintain the order of insertion, simply use a LinkedHashMap. The order in which you put the data is maintained and simply you can iterate over it.
Sample code for LinkedHashMap:
Map<String, String> map = new LinkedHashMap<>();
map.put("key1", "value2");
map.put("key3", "value4");
map.put("key5", "value6");
map.put("key7", "value8");
Set<String> keySet = map.keySet();
for(String st: keySet){
System.out.println(st);
}
for(Map.Entry<String, String> entry : map.entrySet()){
System.out.println(entry.getKey() + " " + entry.getValue());
}
Output:
key1
key3
key5
key7
key1 value2
key3 value4
key5 value6
key7 value8
It has nothing to do with the android OS. The resulting Set of HashMap has no order. However there are Sets with an order e.g. TreeSet.
Related
I am looking for a way to reordering a hashmap...Similar like Swapping two rows of hashmap with their respective key...
My hashmap is like, before swapping
["key1","value1"];
["key2","value2"];
["key3","value3"];
["key4","value4"];
After swapping key 1 and key 2,
["key4","value4"];
["key2","value2"];
["key3","value3"];
["key1","value1"];
I want to swap two rows along with the key.Is it possible in java?
Not possible with hash map.
HashMap doesn't guarantee the ordering. For that you make look into LinkedHashMap.
Swapping with LinkedHashMap
LinkedHashMap<String, String> oldMap = new LinkedHashMap<>();
oldMap.put("key1", "value1");
oldMap.put("key2", "value2");
oldMap.put("key3", "value3");
oldMap.put("key4", "value4");
System.out.println(oldMap);
ArrayList<String> keySetList = new ArrayList<>();
keySetList.addAll(oldMap.keySet());
Collections.swap(keySetList, 0, 3);
// our output map
LinkedHashMap<String, String> swappedMap = new LinkedHashMap<>();
for(String oldSwappedKey:keySetList) {
swappedMap.put(oldSwappedKey, oldMap.get(oldSwappedKey));
}
System.out.println(swappedMap);
Swapping 1 and 4
Input map:{key1=value1, key2=value2, key3=value3, key4=value4}
Output map:{key4=value4, key2=value2, key3=value3, key1=value1}
Perhaps something like this? Parametrize the keys, but this should end up "swapping" values behind key1 and key2.
private void test(HashMap<MyKey, MyValue> map) {
Set<MyKey> keyset = map.keySet();
MyKey key1 = keyset.get(0);
MyKey key2 = keyset.get(1);
MyValue val1;
MyValue val2;
if (map.containsKey(key1)) {
val1 = map.get(key1);
}
if (map.containsKey(key2)) {
val2 = map.get(key2);
}
if (val2 != null)
map.put(key1, val2);
if (val1 != null)
map.put(key2, val1);
}
I am trying to traverse a Hash map in decreasing order or in increasing order but I am not getting the proper output.
Here is my map:
Hashmap<String Integer> hm= new Hashmap<String,Integer>();
Here are my values:
Key Value
Hi 4
kumar 1
Hello 1
vivek 3
I am trying something like:
List<Integer> ValueList = new ArrayList<Integer>(hm.values());
ArrayList<String> keyList = new ArrayList<String>(hm.keySet());
Collections.sort(ValueList);
Collections.reverse(keyList);
Collections.reverse(ValueList);
and I want this something like:
Key Value
kumar 1
Hello 1
vivek 3
Hi 4
I recommend using the Apache Commons Collections ListOrderedMap. Here's the solution:
//Populate the map
Map<String, Integer> map = new HashMap<>();
map.put("Hi", 4);
map.put("kumar", 1);
map.put("Hello", 1);
map.put("vivek", 3);
//Sort the values
List<Integer> values = new ArrayList<Integer>(map.values());
Collections.sort(values);
int size = values.size();
Set<Entry<String, Integer>> entries = map.entrySet();
//Create a new ordered map
ListOrderedMap<String, Integer> orderedMap;
orderedMap = ListOrderedMap.listOrderedMap(new HashMap<String, Integer>(map));
for (int i = 0; i < size; i++) {
Integer value = values.get(i);
Iterator<Entry<String, Integer>> iter = entries.iterator();
while (iter.hasNext()) {
Entry<String, Integer> entry = iter.next();
if (value.equals(entry.getValue())) {
//Put all values at index i that match the value
orderedMap.put(i, entry.getKey(), value);
}
}
}
//Print the orderedMap key/value pairs
entries = orderedMap.entrySet();
for (Entry<String, Integer> entry : entries) {
final String key = entry.getKey();
final Integer value = entry.getValue();
System.out.println("key = " + key + ", value = " + value);
}
Output:
key = Hello, value = 1
key = kumar, value = 1
key = vivek, value = 3
key = Hi, value = 4
You can view a Map as a set of entries, where each entry has a key and a value. So what you want is a sorted list of entries. You can't just sort keys or values, as you would lose the association between the key and the value:
List<Map.Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());
entries.sort(Comparator.comparing(Map.Entry::getValue));
If you need to access these values often, you can avoid the sort by using a TreeMap object.
http://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html
This special Map can be used like a normal HashMap with the additional feature that it will sort your keys automatically using their Comparable, Equals and Hash methods (which you have to override)
If you define your own Key Class, you can make it so it will sort your values automatically.
If you don't need this performance boost, extracting the values then sorting them with Collections.sort works well too.
There is a HashMap:
HashMap aircraftHandling = new HashMap<String, HashMap<Double, Integer>>();
This HashMap contains the following entries:
HashMap<"M", HashMap<1.22, 200>>();
HashMap<"M", HashMap<5.62, 300>>();
HashMap<"L", HashMap<10.11, 900>>();
I need to get entries for the key "M", i.e. HashMap<1.22, 200> and HashMap<5.62, 300>. I do this in the following way:
HashMap lines = (HashMap<Double, Integer>) aircraftHandling.get("M");
The question is how to get Double and Integer, ie (1.22, 200) and (5.62, 300), into two separate variables?
for (int i=0; i<lines.size(); i++)
{
//doubleValue = [i]???
//integerValue = [i]???
}
You can use an enhanced for loop just to read elements :
for (Map.Entry<Double, Integer> entry : lines.entrySet()) {
Double key = entry.getKey();
Integer value = entry.getValue();
}
This HashMap contains the following entries:
HashMap<"M", HashMap<1.22, 200>>();
HashMap<"M", HashMap<5.62, 300>>();
HashMap<"L", HashMap<10.11, 900>>();
I need to get entries for the key "M", i.e. HashMap<1.22, 200> and HashMap<5.62, 300>. I do this in the following way:
Not considering the syntax used , since the key is a String , the second time you try to put() a value in the Map using a String key which already exists in Map the new value will override the old value.
This is how you would extract a key-value pair of the HashMap by iterating over a keyset:
Iterator<Double> it= lines.keySet().iterator();
while (it.hasNext()) {
Double key= it.next();
Integer value= lines.get(key);
}
On the side note, I don't know if this is an error, or just a bad representation of your data:
HashMap<"M", HashMap<1.22, 200>>();
HashMap<"M", HashMap<5.62, 300>>();
But if it is how it looks, this is impossible. A Map can have a single value for a single key! That means, if you put some value for a key "M" and you do it again for the same key, the latter will overwrite the previous value. What you should do is:
//get the inner map for "M"
HashMap<Double, Integer> innerMap= aircraftHandling.get("M");
if (innerMap == null) {
//if it does not exist instantiate it
innerMap= new HashMap<Double, Integer>();
aircraftHandling.put("M", innerMap);
}
and now, in the innerMap you add other values, e.g.:
innerMap.put(1.22, 200);
innerMap.put(5.62, 300);
Try maybe this way
Map<Double, Integer> lines = (HashMap<Double, Integer>) aircraftHandling.get("M");
// ^add this generic types here so you wont have to cast them later with getters
for (Map.Entry<Double, Integer> entry:lines.entrySet()){
Double key = entry.getKey();
Integer value = entry.getValue();
}
Here you have it:
HashMap<String, HashMap<Double, Integer>> aircraftHandling = new HashMap<String, HashMap<Double, Integer>>();
HashMap<Double, Integer> subMap1 = new HashMap<Double, Integer>();
subMap1.put(1.22, 200);
HashMap<Double, Integer> subMap2 = new HashMap<Double, Integer>();
subMap1.put(5.62, 300);
aircraftHandling.put("M", subMap1);
aircraftHandling.put("L", subMap2);
HashMap<Double, Integer> lines = aircraftHandling.get("M");
for (Entry<Double, Integer> set : lines.entrySet()) {
Double doubleValue = set.getKey();
Integer integerValue = set.getValue();
}
First, Map can't have duplicate key. If you insert duplicate key then previous one will disappear. You can use following code to separate key and value:
HashMap lines = (HashMap<Double, Integer>) aircraftHandling.get("M");
for(Map.Entry<Double, Integer> entry: lines ){
doubleValue = entry.getKey();
integerValue =entry.getValue();
}
with a foreach loop and method HashMap.entrySet() :
HashMap<Double, Integer> map=...
for(Entry<Double,Integer> entry : map.entrySet()){
Double d = entry.getKey();
Integer i = entry.getValue();
}
You cannot have 2 values for the key M. I hope you've taken care of that while putting the values. You should have put one hashmap for the value M.
You simply need to fetch the hashmap corresponding to key M
HashMap lines = (HashMap<Double, Integer>) aircraftHandling.get("M");
And then iterate over all entries in this map
Iterator it = lines.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
double d = pairs.getKey().doubleValue();
int i = pairs.getValue().intValue();
}
EDIT - Had answered from my mobile so missed a few details. Adding them now.
Good day, this is kind of confusing me now(brain freeze!) and seem to be missing something. Have an ArrayList which i populate with a HashMap. now i put in my HashMap and arraylist.
Map.put(DATE, value1);
Map.put(VALUE, value2);
arraylist.put(Map);
Since am parsing a JSON, the arraylist increases in significant size. now my question is how do you get the values from both map keys in the arraylist? i have tried this
if(!list.isEmpty()){ // list is an ArrayList
for(int k = 0; k < list.size(); k++){
map = (HashMap)list.get(k);
}
}
Log.d(TAG, "map size is" + map.size());
String [] keys = new String[map.size()];
String [] date_value = new String[map.size()];
String [] value_values = new String[map.size()];
int i = 0;
Set entries = map.entrySet();
Iterator iterator = entries.iterator();
while(iterator.hasNext()){
Map.Entry mapping = (Map.Entry)iterator.next();
keys[i] = mapping.getKey().toString();
date_value[i] = map.get(keys[i]);
if(keys[i].equals(DATE)){
date_value[i] = map.get(keys[i]);
} else if(keys[i].equals(VALUE)){
value_values[i] = map.get(keys[i]);
}
i++;
}
But i can't seem to get all the values. the Map size always return a value of 2, which is just the elements. how can i get all the values from the Map keys in the ArrayList? Thanks
Why do you want to re-invent the wheel, when you already have something to do your work. Map.keySet() method gives you a Set of all the keys in the Map.
Map<String, Integer> map = new HashMap<String, Integer>();
for (String key: map.keySet()) {
System.out.println("key : " + key);
System.out.println("value : " + map.get(key));
}
Also, your 1st for-loop looks odd to me: -
for(int k = 0; k < list.size(); k++){
map = (HashMap)list.get(k);
}
You are iterating over your list, and assigning each element to the same reference - map, which will overwrite all the previous values.. All you will be having is the last map in your list.
EDIT: -
You can also use entrySet if you want both key and value for your map. That would be better bet for you: -
Map<String, Integer> map = new HashMap<String, Integer>();
for(Entry<String, Integer> entry: map.entrySet()) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
P.S.: -
Your code looks jumbled to me. I would suggest, keep that code aside, and think about your design one more time. For now, as the code stands, it is very difficult to understand what its trying to do.
List constructor accepts any data structure that implements Collection interface to be used to build a list.
To get all the keys from a hash map to a list:
Map<String, Integer> map = new HashMap<String, Integer>();
List<String> keys = new ArrayList<>(map.keySet());
To get all the values from a hash map to a list:
Map<String, Integer> map = new HashMap<String, Integer>();
List<Integer> values = new ArrayList<>(map.values());
Try it this way...
I am considering the HashMap with key and value of type String, HashMap<String,String>
HashMap<String,String> hmap = new HashMap<String,String>();
hmap.put("key1","Val1");
hmap.put("key2","Val2");
ArrayList<String> arList = new ArrayList<String>();
for(Map.Entry<String,String> map : hmap.entrySet()){
arList.add(map.getValue());
}
Create an ArrayList of String type to hold the values of the map. In its constructor call the method values() of the Map class.
Map <String, Object> map;
List<Object> list = new ArrayList<Object>(map.values());
Put i++ somewhere at the end of your loop.
In the above code, the 0 position of the array is overwritten because i is not incremented in each loop.
FYI: the below is doing a redundant search:
if(keys[i].equals(DATE)){
date_value[i] = map.get(keys[i]);
} else if(keys[i].equals(VALUE)){
value_values[i] = map.get(keys[i]);
}
replace with
if(keys[i].equals(DATE)){
date_value[i] = mapping.getValue();
} else if(keys[i].equals(VALUE)){
value_values[i] = mapping.getValue()
}
Another issue is that you are using i for date_value and value_values. This is not valid unless you intend to have null values in your array.
This is incredibly old, but I stumbled across it trying to find an answer to a different question.
my question is how do you get the values from both map keys in the arraylist?
for (String key : map.keyset()) {
list.add(key + "|" + map.get(key));
}
the Map size always return a value of 2, which is just the elements
I think you may be confused by the functionality of HashMap. HashMap only allows 1 to 1 relationships in the map.
For example if you have:
String TAG_FOO = "FOO";
String TAG_BAR = "BAR";
and attempt to do something like this:
ArrayList<String> bars = ArrayList<>("bar","Bar","bAr","baR");
HashMap<String,String> map = new HashMap<>();
for (String bar : bars) {
map.put(TAG_BAR, bar);
}
This code will end up setting the key entry "BAR" to be associated with the final item in the list bars.
In your example you seem to be confused that there are only two items, yet you only have two keys recorded which leads me to believe that you've simply overwritten the each key's field multiple times.
Suppose I have Hashmap with key datatype as KeyDataType
and value datatype as ValueDataType
HashMap<KeyDataType,ValueDataType> list;
Add all items you needed to it.
Now you can retrive all hashmap keys to a list by.
KeyDataType[] mKeys;
mKeys=list.keySet().toArray(new KeyDataType[list.size()]);
So, now you got your all keys in an array mkeys[]
you can now retrieve any value by calling
list.get(mkeys[position]);
Java 8 solution for produce string like "key1: value1,key2: value2"
private static String hashMapToString(HashMap<String, String> hashMap) {
return hashMap.keySet().stream()
.map((key) -> key + ": " + hashMap.get(key))
.collect(Collectors.joining(","));
}
and produce a list simple collect as list
private static List<String> hashMapToList(HashMap<String, String> hashMap) {
return hashMap.keySet().stream()
.map((key) -> key + ": " + hashMap.get(key))
.collect(Collectors.toList());
}
It has method to find all values from map:
Map<K, V> map=getMapObjectFromXyz();
Collection<V> vs= map.values();
Iterate over vs to do some operation
I have a HashMap, which contains another HashMap. I want to iterate over the first HashMap and use the Key values from that. Then, as I iterate over the first HashMap I want to start an inner loop iterating over the second HashMap, getting all the values.
The problem I have so far is that I can't figure out how to get the keys from the Iterator.
HashMap<String, HashMap<Integer, String>> subitems = myHashMap.get("mainitem1");
Collection c = subitems.values();
Iterator itr = c.iterator();
while(itr.hasNext())
{
// Get key somehow? itr.getKey() ???
// contains the sub items
HashMap productitem = (HashMap)itr.next();
}
The data that i get from subitems is this:
{Item1{0=sub1, 1=sub2}, Item2{0=sub3, 1=sub4}}
Then, in the while loop productitem contains the 'sub items'. But i can't find out where i can get the key value 'Item1' and 'Item2' from.
How can i get those?
You can't get the key from values().iterator().
You need to use entrySet().iterator(). That will return Map.Entry<K,V> objects on which you can call getKey() and getValue().
for (Map.Entry<Integer,Key> entry : subitems.keySet()) {
Integer key = entry.getKey();
String value = entry.getValue();
// do stuff
}
I'd also like to add that having deeply nested maps of lists of maps is usually a sign that you really want to write custom classes to hold your data. Especially when the maps have pre-defined keys to be used and interpretation of the values in the lists depends on the position within the list! I call this code smell "object denial".
You can't go from value to key in a map. (There may be several keys mapping to the same value!)
You can iterate over the map entries though using subitems.entrySet().iterator(), or you can iterate over the keys, and in each iteration retrieve the associated value through subitems.get(key).
You could do something like this (using iterators):
Set<Entry<String, HashMap<Integer, String>>> c = subitems.entrySet();
Iterator<Entry<String, HashMap<Integer, String>>> iterator = c.iterator();
while(iterator.hasNext())
{
Entry<String, HashMap<Integer, String>> entry = iterator.next();
System.out.println("key:" + entry.getKey());
HashMap<Integer, String> innerMap = entry.getValue();
if (innerMap == null) {
continue;
}
Iterator<Entry<Integer, String>> innerIterator = innerMap.entrySet().iterator();
while (innerIterator.hasNext()) {
Entry<Integer, String> innerEntry = innerIterator.next();
System.out.println("key:" + innerEntry.getKey() + " value: " + innerEntry.getValue());
}
}
or like this using foreach structure:
for (Entry<String, HashMap<Integer,String>> entry : subitems.entrySet())
{
System.out.println("key:" + entry.getKey());
HashMap<Integer, String> innerMap = entry.getValue();
if (innerMap == null) {
continue;
}
for (Entry<Integer, String> innerEntry : innerMap.entrySet())
System.out.println("key:" + innerEntry.getKey() + " value: " + innerEntry.getValue());
}
}
java Collections provide facility of EntrySet. This is a list of objects which contain individual keys and values as its properties. You can take a iterator out of this list.
You can get keys as follows.
Iterator i= subitems.entrySet().iterator();
while(i.hasNext()){
String key= i.next().getkey();
}
You can iterate over entries using entrySet().iterator() on the first HashMap or get the keys and iterate over them: Instead of subitems.values().iterator() use subitems.keys().iterator() and use the next key to get the inner hashmap.