i want to create a list that each row contain an array like this :
key1 ->value1
key2 ->value2
key3 ->value3
(key and value are string)
How can i do this ?
If your key must be a String, then you want to use a Map rather than an array. And you want/need a List<Map<String, String>>.
Here's an example:
//declaring and initializing the list of maps
//line below works for Java 7
//List<Map<String, String>> listOfMaps = new ArrayList<>();
//if you want/need to use Java 6 then use the following
List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
//declaring, initializing and filling a map
//line below works for Java 7
//Map<String, String> map1 = new HashMap<>();
//if you want/need to use Java 6 then use the following
Map<String, String> map1 = new HashMap<String, String>();
map1.put("name", "Luiggi");
map1.put("lastname", "Mendoza");
map1.put("maintag", "Java");
//declaring, initializing and filling another map
//line below works for Java 7
//Map<String, String> map2 = new HashMap<>();
//if you want/need to use Java 6 then use the following
Map<String, String> map2 = new HashMap<String, String>();
map2.put("name", "Foo");
map2.put("lastname", "Bar");
map2.put("maintag", "Scala"); //I have nothing against scala
//add maps into the list
listOfMaps.add(map1);
listOfMaps.add(map2);
//Show contents of the list and map
System.out.println(listOfMaps);
//Traverse each element of the List to access key and value
int index = 0;
//it is better to use Iterator or enhanced for each than using List#get(index)
for (Map<String, String> map : listOfMaps) {
System.out.println("Printing element " + index++);
for(Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
System.out.println("--------------------------");
}
You can use an
ArrayList<Map<String, String>>()
This would have the following structure
List index 0: Key1 -> value 1, Key2 -> value 2
List index 1: Key3 -> value 3
So to put a key value pair:
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
Map<String, String> map = new HashMap<String, String>();
map.put(key, value);
map.put(key1, value1);
list.add(map);
So to get a value from a key in the first index of the list:
String value = list.get(0).get(key)
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "1");
map.put("key2", "2");
Map<String, String> anotherMap = new HashMap<String, String>();
anotherMap .put("key3", "3");
anotherMap .put("key4", "4");
List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
listOfMaps.add(map);
listOfMaps.add(anotherMap);
Why do you need this list? What do you need to do with it? Or is this just an exercise?
Related
I have an object with structure
List<Map<String(k1), Map<String(k2), String(v2)>>>
I need to convert the above list to
List<Map<String(k2), Map<String(k1), String(v2)>>>
I am stuck on how do i get the nested map using construct like
serviceResults.stream().map((k, v) -> ????)
that will allow me to swap the keys. Is it possible to do it in a way without using loops using Java 8 streams?
Additional Info
This is the code that uses loop construct
List<Map<String, Map<String, String>>> serviceResults = new ArrayList<>();
//Populate the above list
Map<String, Map<String, String>> swpMapOuter = new HashMap<>();
Map<String, String> swpMapInner = new HashMap<>();
for (Map<String, Map<String, String>> stringMapMap : serviceResults) {
for (Map.Entry<String, Map<String, String>> s : stringMapMap.entrySet()) {
String key1 = s.getKey();
Map<String, String> value1 = s.getValue();
for (Map.Entry<String, String> s1 : value1.entrySet()) {
String key2 = s1.getKey();
String value2 = s1.getValue();
swpMapInner.put(key1, value2);
swpMapOuter.put(key2, swpMapInner);
}
}
}
System.out.println("swpMapOuter " + swpMapOuter);
Below is the code with forEach, instead of for loops, but was wondering, if it could be implemented using Stream constructs
Map<String, Map<String, String>> swpMapOuter2 = new HashMap<>();
Map<String, String> swpMapInner2 = new HashMap<>();
serviceResults.forEach((stringMapMap) -> {
stringMapMap.entrySet().forEach((s) -> {
String key1 = s.getKey();
Map<String, String> value1 = s.getValue();
value1.entrySet().forEach((s1) -> {
String key2 = s1.getKey();
String value2 = s1.getValue();
swpMapInner2.put(key1, value2);
swpMapOuter2.put(key2, swpMapInner2);
});
});
});
System.out.println("swpMapOuter2 " + swpMapOuter2);
I am trying to set a hashmap to have key as string and a list array as value. Is it possible? and how do I set the list into the value?
HashMap<String, List<String>> foo = new HashMap<String, List<String>>();
foo.put("key1",{"key1_value1","key1_value2"});
You can do the following
Map<String, List<String>> foo = new HashMap<String, List<String>>();
List<String> list = new ArrayList<String>();
list.add("key1_value1");
list.add("key1_value2");
foo.put("key1",list);
foo.put("key", Arrays.asList("key1_val1", "key1_val2"));
You have to use a data structure like ArrayList or just an array maybe to represent the list of strings as value.
You can use the following with a List;
foo.put("key", Arrays.asList("key1_val1", "key1_val2"));
where foo is of type Map<String, List<String>>
Or you the following with an array;
foo.put("key", new String[]{"key1_val1", "key1_val2"});
where foo is of type Map<String, String[]>
Map<String, List<String>> foo = new HashMap<String, List<String>>();
List<String> list = new ArrayList<String>();
list.add("value1");
list.add("value2");
foo.put("key1", list);
for (Entry<String, List<String>> entry : foo.entrySet()) {
String key = entry.getKey();
List<String> valueList = entry.getValue();
System.out.println("key = " + key);
for (String value : valueList) {
System.out.println("value = " + value);
}
}
Output
key = key1
value = value1
value = value2
I have a map in which key is list of values and matched to one value as shown below basically i want to create a map in which value will again will be of type map
Deaswe = DealDate
TradeRe = TradeRef
Deadery = DealDate
Dealdt = DealDate
Traes = TradeRef
TraRef = TradeRef
Daelet = DealDate
TF = TradeRef
below is the code to achieve that
Map<String, List<String>> dataMap = new HashMap<String, List<String>>();
dataMap.put ("TradeRef", Arrays.asList("TradeRe", "TraRef", "TF", "Traes"));
dataMap.put ("DealDate", Arrays.asList("Dealdt", "Daelet", "Deadery", "Deaswe"));
Map<String, String> itemMap = new HashMap<String, String>(); //New map for item->key mapping
for(String key: dataMap.keySet()) //Get all keys and iterate through
for(String item: dataMap.get(key)) //For each item in your value list
itemMap.put(item, key); //Create new mapping item->key
now the above map is working fine but over it again i want to create one more map such that as shown below so please advise how can I create a map in which value will be type of my above existing map
key value
B1 HashMap<String, List<String>>
so it would be like
B1 --> Deaswe --> DealDate
B2 ---> Dealdt --> DealDate
B1 ---> TradeRe --> TradeRef
B2 ---> Traes --> TradeRef
folks please advise
You can create a map of your map containing the list:
Map<String, Map<String, List<String>>> mapOfMapOfStrings =
new HashMap<String, Map<String, List<String>>>();
HashMap<String, List<String>> b1Map = new HashMap<String, List<String>>();
mapOfMapOfStrings.put("B1", b1Map);
HashMap<String, List<String>> b2Map = new HashMap<String, List<String>>();
mapOfMapOfStrings.put("B2", b2Map);
ArrayList<String> dealDateList = new ArrayList<String>();
ArrayList<String> tradeRefList = new ArrayList<String>();
b1Map.put("Deaswe", dealDateList);
b2Map.put("Dealdt", dealDateList);
b1Map.put("TradeRe", tradeRefList);
b2Map.put("Traes", tradeRefList);
dealDateList.add("DealDate1");
dealDateList.add("DealDate2");
tradeRefList.add("tradeRef1");
tradeRefList.add("tradeRef2");
You can have a map of string (key)and map (value)
example
Map<String, Map<String, String>> dataMap = new HashMap<String, HashMap<String, String>>();
Map<String, String> itemMap = new HashMap<String, String>();
item="some value";
key="some value";
itemMap.put(item, key);
dataMap.put("TradeRef",itemMap);
this is just an exapmle. i'm using a itemmap inside datamap. you can use multiple levels of maps and insert it as the values in each level of map.
you can also refer to this question Map of maps - how to keep the inner maps as maps? and this link http://java.dzone.com/articles/hashmap-%E2%80%93-single-key-and
Could someone help me out in getting the correct list with no duplicates.
I have a list of hash map say "HashMap map" whose size is 4.
The key value pair is something similar to the below
("uri_path","/shophome/index")
("AvgResp","30.00")
("count", "3");
("status","200");
I want to create another List of Hashmap which contains single entry for "uri_path" and the average and count calculated accordingly. This is what i am trying out.Ideally the size of the new list should be lesser than the original .Can someone help understand were it is going wrong
HashMap<String, String> processedMap = null;
List<HashMap<String, String>> artProcessedEvents=new ArrayList<HashMap<String, String>>();
for (HashMap<String, String> map : artEvents) {// list that contains the values
processedMap = new HashMap<String, String>();
String uri_path= map.get("uri_path");
Double art = Double.parseDouble(map.get("avgRespT"));
count =Integer.parseInt(map.get("count"));
if (processedMap.containsValue(uri_path)){
Double artFromMap = Double.parseDouble(processedMap.get("avgRespT"));
int countFromMap =Integer.parseInt(processedMap.get("count"));
count = count+countFromMap;
art = ((art*count) + (artFromMap*countFromMap))/count;
}
processedMap.put("uri_path",uri_path);
processedMap.put("avgRespT",String.valueOf(art));
processedMap.put("count", String.valueOf(count));
artProcessedEvents.add(processedMap);
}
}
Try this code:
List<HashMap<String, String>> artEvents = ...;
//this map stores all of the result maps (one map per uri_path, uri_path is the key in this uniqueUriMap, map itself being a value).
HashMap<String, HashMap<String, String>> uniqueUriMap = new HashMap<String, HashMap<String, String>>();
for (HashMap<String, String> mapBeingProcessed : artEvents)
{
String uri_path = mapBeingProcessed.get("uri_path");
Double art = Double.parseDouble(mapBeingProcessed.get("avgRespT"));
Integer count =Integer.parseInt(mapBeingProcessed.get("count"));
if (uniqueUriMap.containsKey(uri_path))
{
Double artFromMap = Double.parseDouble(uniqueUriMap.get(uri_path).get("avgRespT"));
int countFromMap = Integer.parseInt(uniqueUriMap.get(uri_path).get("count"));
count = count + countFromMap;
art = ((art * count) + (artFromMap * countFromMap)) / count;
}
HashMap<String, String> newUriMap = new HashMap<String, String>();
newUriMap.put("uri_path",uri_path);
newUriMap.put("avgRespT",String.valueOf(art));
newUriMap.put("count", String.valueOf(count));
uniqueUriMap.put(uri_path, newUriMap);
}
//result list.
List<HashMap<String, String>> artProcessedEvents=new ArrayList<HashMap<String, String>>();
artProcessedEvents.addAll(uniqueUriMap.values());
The problem was with storing the temp values. This:
if (processedMap.containsValue(uri_path))
always returned false as you initialized processedMap inside the loop.
Here is the problem,
if (processedMap.containsValue(uri_path)){
Double artFromMap = Double.parseDouble(processedMap.get("avgRespT"));
int countFromMap =Integer.parseInt(processedMap.get("count"));
count = count+countFromMap;
art = ((art*count) + (artFromMap*countFromMap))/count;
}
You have to get the value from the "map" (for loop variable) and manipulate it. And also processedMap will be empty for every run and that needs to be removed.
You seem to be confusing yourself a lot here but this would help.
In order to remove duplicates and update your parameters you would need to change processedmap from a simple string->string hashmap to a string->Hashmap i.e as shown below.Following that you would need to add it to the list via an iterator.
HashMap<String, HashMap<String, String>> processedMap = new HashMap<String, HashMap<String, String>>();
List<HashMap<String, String>> artProcessedEvents=new ArrayList<HashMap<String, String>>();
for (HashMap<String, String> map : artEvents) {// list that contains the values
String uri_path= map.get("uri_path");
Double art = Double.parseDouble(map.get("avgRespT"));
count =Integer.parseInt(map.get("count"));
if (processedMap.containsValue(uri_path)){
Double artFromMap = Double.parseDouble(processedMap.get("avgRespT"));
int countFromMap =Integer.parseInt(processedMap.get("count"));
count = count+countFromMap;
art = ((art*count) + (artFromMap*countFromMap))/count;
}
//Create a new Hashmap
HashMap<String, String> updatedMap=new HashMap<String, String>();
updatedMap.put("uri_path",uri_path);
updatedMap.put("avgRespT",String.valueOf(art));
updatedMap.put("count", String.valueOf(count));
processedMap.put(uri_path,updateMap);
}
//Iterate and add elements to the list
for (Map.Entry<String, HashMap<String, String>> entry : processedMap.entrySet())
{
artProcessedEvents.add(entry.getValue());
}
}
Thanks Michal and others your suggestions
The below code solved my issues
List<HashMap<String, String>> artEvents =new ArrayList<HashMap<String, String>>();
//this map stores all of the result maps (one map per uri_path, uri_path is the key in this uniqueUriMap, map itself being a value).
HashMap<String, HashMap<String, String>> uniqueUriMap = new HashMap<String, HashMap<String, String>>();
for (HashMap<String, String> mapBeingProcessed : artEvents)
{
String uri_path = mapBeingProcessed.get("uri_path");
Double art = Double.parseDouble(mapBeingProcessed.get("avgRespT"));
Integer count =Integer.parseInt(mapBeingProcessed.get("count"));
if (uniqueUriMap.containsKey(uri_path))
{
Double artFromMap = Double.parseDouble(uniqueUriMap.get(uri_path).get("avgRespT"));
int countFromMap =Integer.parseInt(uniqueUriMap.get(uri_path).get("count"));
count = count + countFromMap;
art = ((art * count) + (artFromMap * countFromMap)) / count;
}
HashMap<String, String> newUriMap = new HashMap<String, String>();
newUriMap.put("uri_path",uri_path);
newUriMap.put("avgRespT",String.valueOf(art));
newUriMap.put("count", String.valueOf(count));
uniqueUriMap.put(uri_path, newUriMap);
}
//result list.
List<HashMap<String, String>> artProcessedEvents=new ArrayList<HashMap<String, String>>();
artProcessedEvents.addAll(uniqueUriMap.values());
I have a method which is returning List<Map<String,Object>>.
How to iterate over a list like List<Map<String,Object>>?
It sounds like you're looking for something like this:
List<Map<String, Object>> list; // this is what you have already
for (Map<String, Object> map : list) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
}
}
List<Map<String, Object>> list = getMyMap();
for (Map<String, Object> map : list) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
}
Loop through list of maps
Handle map entries
with java 1.8 (8) you can re-write it like:
list.forEach(item ->
item.forEach((k, v) -> System.out.println(k + ": " + (String)v)
);
I'm posting you one simple Example of List<Map<String,Object>>.
public static void main(String[] args){
Map<String,Object> map1 = new HashMap<>();
map1.put("Map1 Key1", (Object) "Map1 value1");
map1.put("Map1 Key2", (Object) "Map1 value2");
Map<String,Object> map2 = new HashMap<>();
map2.put("Map2 Key1", (Object) "Map2 value1");
map2.put("Map2 Key2", (Object) "Map2 value2");
List<Map<String,Object>> list = new ArrayList<>();
list.add(map1);
list.add(map2);
list.stream().forEach(mapsData->{
mapsData.entrySet().forEach(mapData->{
System.out.println("Key:"+mapData.getKey()+ " Value:"+mapData.getValue());
});
});
}
This should work:
List<Map<String, Object>> list = ...
for (Map<String, Object> map : list)
{
...
}
You can also use an iterator or the get method within a for loop to access the elements within the List.
Map<String, String> map = new HashMap<>();
map.put("First", "1");
map.put("Second", "2");
map.put("third", "3");
map.put("four", "4");
// here is the logic
for (Map.Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + " - " + entry.getValue());
}
This is an easy way to iterate over a list of Maps as my starting point. My List had one Map object inside with 3 values
List<Map<String, Object>>
using Java's functional programming in a rather short and succinct manner. The purpose here was to pull out all the maps stored in a list and print them out. I could have also collected the values etc.
answerListOfMaps.stream().map(map -> map.entrySet())
.forEach(System.out::println );
output in Eclipse IDE console looked like this:
[isAllowed=true, isValid=true, cardNumber=672xxxxxxxxxxx]
x's for Obfuscation
alternate way:
answerListOfMaps.stream().flatMap(map -> map.entrySet().stream())
.forEach( entry -> System.out.println(entry.getKey() + ":" + entry.getValue()) );
console:
isAllowed:true
isValid:true
cardNumber:672xxxxxxxxxxx