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
Related
I was wondering if it is possible to get a random value from a HashMap and then straight after remove that key/value from the HashMap? I can't seem to find any method that works, would a different data structure be more appropriate for this?
Edit:
I should've been more clear, I generate a random number and then retrieve the value that corresponds with that random number. I need to return the value and then remove the entry from the map.
Maybe Map#computeIfPresent would work in your case. From its documentation:
If the value for the specified key is present and non-null, attempts to compute a new mapping given the key and its current mapped value.
If the remapping function returns null, the mapping is removed.
var map = new HashMap<Integer, String>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
map.computeIfPresent(2, (k, v) -> {
// `v` is equal to "Two"
return null; // Returning `null` removes the entry from the map.
});
System.out.println(map);
The above code outputs the following:
{1=One, 3=Three}
If you were to use a ConcurrentHashMap, then this would be an atomic operation.
The best way to both return and remove the key-value pair from a HashMap is by using the remove(key) method. This method removes the entry associated with the key and returns its corresponding value.
Integer randomNumber = new Random().nextInt(10);
Map<Integer, String> map = new HashMap<>();
String valueOfRandomNumberKey = map.remove(randomNumber);
The problem, as I understand it, is this: given a HashMap you want to
Choose a key at random from among the the keys currently associated in the Map;
Remove that association of that randomly chosen key from the map; and
Return the value that had, until recently, been associated with that key
Here's an example of how to do this, along with some a little test/demonstration routine:
public class Main
{
private static <K, V> V removeRandomEntry(Map<K, V> map){
Set<K> keySet = map.keySet();
List<K> keyList = new ArrayList<>(keySet);
K keyToRemove = keyList.get((int)(Math.random()*keyList.size()));
return map.remove(keyToRemove);
}
public static void main(String[] args){
Map<String, String> map = new HashMap<>();
for(int i = 0; i < 100; ++i)
map.put("Key" + i, "Value"+i);
int pass = 0;
while (!map.isEmpty())
System.out.println("Pass " + (++pass) + ": Removed: " + removeRandomEntry(map));
}
}
I would do it like this:
Hashmap<Integer, Object> example;
int randomNum = ThreadLocalRandom.current().nextInt(0, example.size());
example.getValue() //do something
example.remove(new Integer(randomNum));
I have a populated hashmap in the form Hashmap<String , ArrayList<Double>>. There are many cases in which the values (Arraylist) are the same. What I want tro do is if the value is same , the two separate entries should be changed to one with a change in the key. For eg:
HashMap<String, ArrayList<Double>> map = new HashMap<>();
ArrayList<Double> arr = new ArrayList<>();
arr.add(1);
arr.add(2)
map.put("a",arr);
map.put("b",arr);
map.put("c",arr);
This should result in a hashmap with a single entry :
{a, b , c=[1,2]}
I have tried to solve this for hours but am still unable to do so. A million thanks in advance.
Creating your custom HashMap by overriding put() should work, performance-wise it is not really efficient though.
Something like this:
public class CustomMap extends HashMap<String, ArrayList<Double>> {
#Override
public ArrayList<Double> put(String key, ArrayList<Double> value) {
for (Entry<String, ArrayList<Double>> entry : entrySet()) {
if (entry.getValue().equals(value)) {
String oldKey = entry.getKey();
remove(oldKey);
String newKey = oldKey + ", " + key;
return super.put(newKey, value);
}
}
return super.put(key, value);
}
}
To use it, just replace the following:
HashMap<String, ArrayList<Double>> map = new HashMap<>();
With:
CustomMap map = new CustomMap();
Maps relate keys with values. So even if the values are the same, you can't combine these entries because the keys are different
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.
I have a hash map that looks like this:
HashMap<String, ArrayList<String>> varX = new HashMap<String, ArrayList<String>>();
And I can't for the life of me work out how to count the number of duplicate values.
For example, If put("001", "DM"); into the hash map and put("010", "DM"); as well, how can count if there are two values int the ArrayList section of the Hashmap.
For example, the output would look something like this:
DM:2 as I 'put' two DM values into the Hashmap.
You have a HashMap that maps String to ArrayList<String>.
Doing put("001", "DM") on this map will not work as was pointed out to you in the comments by #Sotirios Delimanolis.
You would get an error that looks like:
The method put(String, ArrayList<String>) in the type HashMap<String,ArrayList<String>> is not applicable for the arguments (String, String)
Based on your example behavior, you want a HashMap that maps String to String (i.e. put("001", "DM");
Now, assuming you have that:
HashMap<String, String> varX = new HashMap<String, String>();
And you want to count how many keys map to the same value, here's how you can do that:
varX.put("001", "DM");
varX.put("010", "DM");
// ...
int counter = 0;
String countingFor = "DM";
for(String key : varX.keySet()) { // iterate through all the keys in this HashMap
if(varX.get(key).equals(countingFor)) { // if a key maps to the string you need, increment the counter
counter++;
}
}
System.out.println(countingFor + ":" + counter); // would print out "DM:2"
HashMap hm =new HashMap();
hm.put("01","one");
hm.put("02","two");
hm.put("03","one");
hm.put("04","one");
hm.put("05","two");
HashMap newHm = new HashMap();
Iterator it = hm.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
if(newHm.containsKey(pair.getValue())){
newHm.put(pair.getValue(), Integer.parseInt(newHm.get(pair.getValue()).toString())+1 );
}else{
newHm.put(pair.getValue(),1 );
}
it.remove(); // avoids a ConcurrentModificationException
}
As Sotirios says, you can only put an ArrayList.
ArrayList<String> names= new ArrayList<String>();
names.add("Josh");
put("001", names);
If you want to insert Strings into the HashMap, define it as follow:
Map<String,String> example = new HashMap<String,String>();
example.put( "001", new String( "Rooney" ));
Regards,
Collections.frequency(map, "value"); is used to count the passed object in collection.
Following is the declaration of that method:
public static int frequency(Collection<?> c, Object o)
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.