I am having trouble in adding the values of hashmap arraylist if the key is same. I have an arraylist as
ArrayList<HashMap<String, Integer>> expense = new ArrayList<HashMap<String, Integer>>();
The output is as
{food = 300},
{entertainment = 100},
{food = 500}
I want to create a new hashmap arraylist
ArrayList<HashMap<String, Integer>> newExpense = new ArrayList<HashMap<String, Integer>>();
and store
{food= 800},
{entertainment = 100}
I have tried nested loop and all but it didnot work. Can anybody please help me?
you can have a simple hashmap for that...
while putting the values in hashmap, use this code..
if (map.containsKey(key))
map.put(key, map.get(key) + newValue);
else
map.put(key, newValue);
even though it is not recommended, if you still need to do that because of own reasons..
this could be the logic to get new expenses in a hashmap..
ArrayList<HashMap<String, Integer>> expense = new ArrayList<HashMap<String, Integer>>();
HashMap<String, Integer> newExpense = new HashMap<>();
for(HashMap<String, Integer> oldExpense : expense)
{
for(String key : oldExpense.keySet())
{
if (newExpense.containsKey(key))
newExpense.put(key, newExpense.get(key) + oldExpense.get(key));
else
newExpense.put(key, oldExpense.get(key));
}
}
System.out.println(newExpense.toString());
Related
this is my code for detail description.
i get size of Hashmapis ok. but when i try to get ArrayList<Map<String, Object>>> using key, all the ArryList have size 1.
private ArrayList<Map<String, Object>> settingInObject;
private ArrayList<Map<String, Object>> parentItemList;
private HashMap<String, ArrayList<Map<String, Object>>> childItemList;
settingInObject = new ArrayList<>();
parentItemList = new ArrayList<>();
childItemList = new HashMap<String, ArrayList<Map<String,Object>>>();
ArrayList<Map<String, Object>> arrayList = new ArrayList<Map<String, Object>>();
for (Map<String, Object> objectMap : settingInObject) {
if (objectMap.get("IsCheked").toString().equals("1")) {
if (arrayList.size() > 0) {
childItemList.put(parentItemList.get(parentItemList.size()).get("TitleDesc").toString().trim(), arrayList);
arrayList.clear();
}
parentItemList.add(objectMap);
} else {
arrayList.add(objectMap);
}
}
is there i do something wrong??
You are calling
arrayList.clear();
while under arayList you have still reference to added object - in result you are clearing the list that is already put in the map
If you want to have new empty list in arrayList you need to reinstance it rather
arrayList = new ArrayList<Map<String, Object>>();
I am currently facing a problem with my code
I am trying to put in a ArrayList> the values of a Hashmap which gets its values from another arraylist
Here is the code :
ArrayList<HashMap<String, String>> AL_route_bus_collection_a = new ArrayList<HashMap<String,String>>();
HashMap<String,String> HM_route_bus_collection_a = new HashMap<String, String>();
for(int i = 0;i<routeNo_set.size();i++ ) {
HM_route_bus_collection_a.put("route_no", routeNo_set.get(i));
HM_route_bus_collection_a.put("address", address_set.get(i));
HM_route_bus_collection_a.put("bus_type", busType_set.get(i));
AL_route_bus_collection_a.add(HM_route_bus_collection_a);
}
for (HashMap<String, String> hashMap : AL_route_bus_collection_a) {
System.out.println(hashMap.keySet());
for (String key : hashMap.keySet()) {
System.out.println(hashMap.get(key));
}
}
but I am ending up getting only the value routeNo_set(2) ,address_set(2), busType_set(2) in my arraylist repeated 3 times
output screenshot
any help would be very helpfull
thanks in Advance
Your problem come from the fact that you're always using the same map inside your loop, and you store it three times into your ArrayList.
That's why you're getting the same results, because it's the same map and the put() method replace the old value for the key if the provided key already exists in the map.
You have to instanciate a new map each time you go through the loop.
The following code should work :
ArrayList<HashMap<String, String>> AL_route_bus_collection_a = new ArrayList<HashMap<String,String>>();
for(int i = 0;i<routeNo_set.size();i++ ) {
HashMap<String,String> HM_route_bus_collection_a = new HashMap<String, String>();
HM_route_bus_collection_a.put("route_no", routeNo_set.get(i));
HM_route_bus_collection_a.put("address", address_set.get(i));
HM_route_bus_collection_a.put("bus_type", busType_set.get(i));
AL_route_bus_collection_a.add(HM_route_bus_collection_a);
}
for (HashMap<String, String> hashMap : AL_route_bus_collection_a) {
System.out.println(hashMap.keySet());
for (String key : hashMap.keySet()) {
System.out.println(hashMap.get(key));
}
}
The reason why you are getting only one value is that the Hashmap values are overwritten in the loop because duplicate keys are not allowed in HashMap.So you will always get the last index values in your hashmap.
So if want one key with different values you can use HashMap<String, ArrayList<String>>.
Assuming that you want only one key value pair which you want to add in your arraylist.
Here is the example, Read about HashMap
public static void main (String[] args) throws java.lang.Exception
{
ArrayList<HashMap<String, String>> AL_route_bus_collection_a = new ArrayList<HashMap<String,String>>();
HashMap<String,String> HM_route_bus_collection_a = new HashMap<String, String>();
List<String> routeNo_set = new ArrayList<String>();
routeNo_set.add("first");
routeNo_set.add("second");
routeNo_set.add("third");
List<String> address_set = new ArrayList<String>();
address_set.add("A");
address_set.add("B");
address_set.add("C");
List<String> busType_set = new ArrayList<String>();
busType_set.add("1");
busType_set.add("2");
busType_set.add("3");
for(int i = 0;i<routeNo_set.size();i++ ) {
HM_route_bus_collection_a.put("route_no", routeNo_set.get(i));
HM_route_bus_collection_a.put("address", address_set.get(i));
HM_route_bus_collection_a.put("bus_type", busType_set.get(i));
AL_route_bus_collection_a.add(HM_route_bus_collection_a);
HM_route_bus_collection_a = new HashMap<String, String>();
}
for (HashMap<String, String> hashMap : AL_route_bus_collection_a) {
System.out.println(hashMap.keySet());
for (String key : hashMap.keySet()) {
System.out.println(hashMap.get(key));
}
}
}
Check output here
I've a SortedMap<String, String> containing key:ID & value:Name.
Now I want to rearrange the elements of this Map in random fashion & store them in separate map.
// Get a random entry from the SortedMap.
String[] keyArr = student.keySet().toArray();
String key = keyArr[new Random().nextInt(keyArr.length)];
// Use a separate List<String> to store which key has been selected, so that they are not re-selected
But above method does not sound very efficient.
Please suggest.
Thank You
You would need to copy the entrySet into a List and shuffle it. This would give you the elements in a random order.
Now you can push those elements to a new LinkedHashMap - to preserve the random order. Something like the following:
final Map<String, Object> m = new TreeMap<>();
m.put("A", 1);
m.put("B", 1);
m.put("C", 1);
m.put("D", 1);
m.put("E", 1);
m.put("F", 1);
m.put("G", 1);
final List<Map.Entry<String, Object>> e = new ArrayList<>(m.entrySet());
Collections.shuffle(e);
final Map<String, Object> r = new LinkedHashMap<>();
for (Map.Entry<String, Object> entry : e) {
r.put(entry.getKey(), entry.getValue());
}
I'm not sure that I got your question, but you should be able to do something like
Map<String, String> result = new LinkedHashMap<>();
List keys = new ArrayList(map.keySet());
Collections.shuffle(keys);
for (Object o : keys) {
// Access keys/values in a random order
result.put(o, map.get(o));
}
I am new to java and is still in the learning phase.
I have a structure
Map<Long, Map<String, Data>> mapData
Data has 2 fields time and distance
and the Map has a time which is a Long field and map with Identifier and Data
the structure looks like this
{190001919 = {[1= [data1], 2=[data2], 3=[data3]},
190001920={[1=[data4], 2=[data5], 3=[data6]},
1900019121= {[1=[data7], 2=[data8], 3=[data9]}}
and then convert it into a map - Map<String,List<Data>> mpData with
idenifier as key and values as the values where there the identifier was the same.
like
{1= [data1,data4,data7], 2= [data2,data5,data8],3= [data3,data6,data9]}
Could some one please help me?
Update:
With the below code, I get
{1= [data7,data7,data7], 2= [data8,data8,data8],3= [data9,data9,data9]}
instead of
{1= [data1,data4,data7], 2= [data2,data5,data8],3= [data3,data6,data9]}
Code:
public static Map<Long, Map<String, Data>> listData;
public static Map<String, List<Data>> mapData;
public convertMapData(Map<Long, Map<String, Data>> array) {
listData = new HashMap();
listData = array;
mapData = new HashMap<>();
Iterator it = listData.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<Long, Map<String, Data>> pairs = (Map.Entry) it
.next();
Long keyValue = pairs.getKey();
Map inter = pairs.getValue();
Iterator it2 = inter.entrySet().iterator();
while (it2.hasNext()) {
Map.Entry<String, Data> pairs_2 = (Map.Entry) it2
.next();
String identifierK = pairs_2.getKey();
Data resultV = pairs_2.getValue();
if (!(mapData.containsKey(identifierK))) {
mapData.put(identifierK, new ArrayList<Data>());
}
mapData.get(identifierK).add(resultV);
}
}
}
Define Map<String,List<Data>> listData = new HashMap<String, List<Data>>();
Iterate over mapData's values (seems you don't use the keys of that map).
For every value of mapData, which again is a map, iterate over the entrySet, which gives you key (a String, lets call it K) and value (a Data object, lets call it V) of every entry.
Check if your listData already has a key like K (using containsKey()) and if not, add one, using listData.put(K, new ArrayList<Data>())
add V to the list that's stored for the key: listData.get(K).add(V)
That's all. As Rohit Jain commented, you'll not need a list around the listData map.
Try this:
public Map<String, List<Data>> convert(Map<Long, Map<String, Data>> array) {
Map<String, List<Data>> result = new HashMap<String, List<Data>>();
for (Map<String, Data> inter : array.values()) {
for (Map.Entry<String, Data> entry : inter.entrySet()) {
String k = entry.getKey();
String v = entry.getValue();
if (!result.containsKey(k)) {
result.put(k, new ArrayList<Data>());
}
result.get(k).add(v);
}
}
return result;
}
In Java, how does one get the values of a HashMap returned as a List?
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
List<String> list = new ArrayList<String>(map.values());
for (String s : list) {
System.out.println(s);
}
Assuming you have:
HashMap<Key, Value> map; // Assigned or populated somehow.
For a list of values:
List<Value> values = new ArrayList<Value>(map.values());
For a list of keys:
List<Key> keys = new ArrayList<Key>(map.keySet());
Note that the order of the keys and values will be unreliable with a HashMap; use a LinkedHashMap if you need to preserve one-to-one correspondence of key and value positions in their respective lists.
Basically you should not mess the question with answer, because it is confusing.
Then you could specify what convert mean and pick one of this solution
List<Integer> keyList = Collections.list(Collections.enumeration(map.keySet()));
List<String> valueList = Collections.list(Collections.enumeration(map.values()));
Collection Interface has 3 views
keySet
values
entrySet
Other have answered to to convert Hashmap into two lists of key and value. Its perfectly correct
My addition: How to convert "key-value pair" (aka entrySet)into list.
Map m=new HashMap();
m.put(3, "dev2");
m.put(4, "dev3");
List<Entry> entryList = new ArrayList<Entry>(m.entrySet());
for (Entry s : entryList) {
System.out.println(s);
}
ArrayList has this constructor.
Solution using Java 8 and Stream Api:
private static <K, V> List<V> createListFromMapEntries (Map<K, V> map){
return map.values().stream().collect(Collectors.toList());
}
Usage:
public static void main (String[] args)
{
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
map.put(3, "three");
List<String> result = createListFromMapEntries(map);
result.forEach(System.out :: println);
}
If you only want it to iterate over your HashMap, no need for a list:
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
for (String s : map.values()) {
System.out.println(s);
}
Of course, if you want to modify your map structurally (i.e. more than only changing the value for an existing key) while iterating, then you better use the "copy to ArrayList" method, since otherwise you'll get a ConcurrentModificationException. Or export as an array:
HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
for (String s : map.values().toArray(new String[]{})) {
System.out.println(s);
}
If you wanna maintain the same order in your list, say:
your Map looks like:
map.put(1, "msg1")
map.put(2, "msg2")
map.put(3, "msg3")
and you want your list looks like
["msg1", "msg2", "msg3"] // same order as the map
you will have to iterate through the Map:
// sort your map based on key, otherwise you will get IndexOutofBoundException
Map<String, String> treeMap = new TreeMap<String, String>(map)
List<String> list = new List<String>();
for (treeMap.Entry<Integer, String> entry : treeMap.entrySet()) {
list.add(entry.getKey(), entry.getValue());
}
I use usually map.values() to get values, then convert them to list
let say you have this Hashmap:
HashMap<String, Integer> map = new HashMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);
You can get values from the map, then convert them to a list in one code line like that:
List<Integer> values = map.values().stream()
.collect(Collectors.toList());