Cast Map including Collections - java

Code below seems to work casting map_b to map_a, but is there a better solution?
Map<Integer,List<MyClass>> map_a = new HashMap<>();
Map<Integer,List<Object>> map_b = factory.createMapWithMyClasses();
for(Map.Entry<Integer, List<Object>> entry : map_b.entrySet())
{
map_a.put(entry.getKey(), (List<MyClass>) (List) entry.getValue());
}

You can use ? instead of Object.
Map<Integer,List<MyClass>> map_a = new HashMap<>();
Map<Integer,List<?>> map_b = factory.createMapWithMyClasses();
for(Map.Entry<Integer, List<?>> entry : map_b.entrySet()){
map_a.put(entry.getKey(), (List<MyClass>) entry.getValue());
}

Related

How to iterate List<Map<String, Object>> and add the key and value dynamically in another hash map in java

I'm trying to iterate the List<Map<String, Object>> and want to check if the code is "approved" or not - if code is having value "approved" then I would like to add "id" as Key and "date" as Value in another hashMap.
List<Map<String, Object>> prodIds = ((List<Map<String, Object>>) myIds.get("result"));
This prodIds returns below set of records:
[{id=[14766724], Date=[1999-01-01]}, {id=[49295837], code=[approved], Date=[2003-04-01]}]
[{id=[58761474621], code=[approved], Date=[2017-09-30]}, {id=[3368781], code=[Cancelled], Date=[2014-01-01]}, {id=[48843224], code=[Cancelled], Date=[2009-01-01]}]
I want the output something like this: If code is "approved" - my new hash map should have value like below:
map.put("49295837", "2003-04-01")
map.put("58761474621", "2017-09-30")
Java Code
List<Map<String, Object>> prodIds = ((List<Map<String, Object>>) myIds.get("result"));
System.out.println("prodIds : " +prodIds );
// [{id=[14766724], Date=[1999-01-01]}, {id=[49295837], code=[approved], Date=[2003-04-01]}]
// [{id=[58761474621], code=[approved], Date=[2017-09-30]}, {id=[3368781], code=[Cancelled], Date=[2014-01-01]}, {id=[48843224], code=[Cancelled], Date=[2009-01-01]}]
Map<String, String> newMap = new HashMap<>();
for (Map<String, Object> map : prodIds) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
System.out.println("Key : " +key);
String value = (String) entry.getValue();
System.out.println(" Value : " +value);
}
}
I'm having difficulty how to put the key(id) and value(Date) dynamically if the code value is "approved" into new hash map. It would be really helpful if someone can help me with this.
Appreciated your help in advance!
Thanks
As best as I can determine by your example, this should work. But for each Map<String,Object> I need to know what Object is (e.g. String, List<>, etc).
I am assuming they are lists. If I'm wrong you will get a ClassCastException
public static Map<String, String>
getApproved(List<Map<String, Object>> prodIds) {
Map<String, String> newMap = new HashMap<>();
for (Map<String, Object> map : prodIds) {
if (map.containsKey("code") &&
((List<String>) map.get("code")).get(0)
.equals("approved")) {
newMap.put(((List<String>) map.get("id")).get(0),
(String) ((List<String>) map.get("Date"))
.get(0));
}
}
return newMap;
}
Map<String, String> newMap = getApproved(prodIds);
newMap.entrySet().forEach(System.out::println);
Prints
58761474621=2017-09-30
49295837=2003-04-01
It would help if you could describe all your data structures. Like what is the Object type of map?

concurrent modification exception while iterating list map string object and edit key

I'm putting in a List<Map<String, Object>> the result of a query along with the column names. Sometimes column names are like TableAlias.ColumnName, in that case I want to change it to just ColumnName and remove TableAlias. for that I have below code:
queryResult = namedParameterJdbcTemplateHive.queryForList(query, paramSource);
for (Map<String, Object> map : queryResult) {
for (Map.Entry<String, Object> entry : map.entrySet()) {
String[] keyData = entry.getKey().split("\\.");
if (keyData.length > 0) {
Object obj = map.remove(entry.getKey());
map.put(keyData[1], obj);
}
}
}
That is giving me concurrent modification exception so I was trying with an iterator like below:
for (Map<String, Object> map : queryResult) {
for(Iterator<Map.Entry<String, Object>> it = map.entrySet().iterator(); it.hasNext(); ) {
Map.Entry<String, Object> entry = it.next();
String[] keyData = entry.getKey().split("\\.");
if (keyData.length > 0) {
it.remove();
}
}
}
But not sure how to add the item back with the new key.
Any suggestions please?
I would iterate over the original map and fill another map with the updated keys.
queryResult = namedParameterJdbcTemplateHive.queryForList(query, paramSource);
Map<String, Object> newMap = new HashMap<>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
String[] keyData = entry.getKey().split("\\.");
if (keyData.length > 1) {
newMap.put(keyData[1], entry.getValue());
} else {
newMap.put(entry.getKey(), entry.getValue());
}
}

Convert Entry<String, List<String>> to Entry<String, String>

I am trying to store the header name and it's first value as an Entry into a list. I am not sure how to achieve this.
HttpHeaders headerNames = request.getHeaders();
List<Entry<String, String>> reqHeaders = new ArrayList<>();
for (Entry<String, List<String>> entry : headerNames.entrySet()) {
reqHeaders.add(entry.getKey(), entry.getValue().get(0)); //This line is incorrect
}
Starting from Java 9, there is a new utility method allowing to create an immutable entry which is Map#entry(Object, Object).
for (Map.Entry<String, List<String>> entry : headerNames.entrySet()) {
reqHeaders.add(Map.entry(entry.getKey(), entry.getValue().get(0)));
}
For before Java 9, you can use AbstractMap.SimpleImmutableEntry or AbstractMap.SimpleEntry
for (Map.Entry<String, List<String>> entry : headerNames.entrySet()) {
reqHeaders.add(new SimpleImmutableEntry<>(entry.getKey(), entry.getValue().get(0))); // immutable
reqHeaders.add(new SimpleEntry<>(entry.getKey(), entry.getValue().get(0))); // mutable version
}
I tried something like this, but #azro answer is simpler.
HttpHeaders headerNames = request.getHeaders();
Map<String, String> headersMap = new HashMap<>();
List<Entry<String, String>> requestHeaders = new ArrayList<>();
for (Entry<String, List<String>> entry : headerNames.entrySet()) {
headersMap.put(entry.getKey(), entry.getValue().get(0));
}
requestHeaders.addAll(headersMap.entrySet());

Convert Map to ImmutableSetMultimap

I am trying to convert the following piece of code to use ImmutableSetMultimap, but I run into problems when I try to do map.get(...).add(...) because its immutable. Is there an easy way to do this?
List<MyObject> objects
Map<Long, Set<Key>> map = new HashMap<Long, Set<Key>>();
for (MyObject entry : objects) {
if (map.containsKey(entry.getId())) {
map.get(entry.getId()).add(entry.getKey());
} else {
Set<Key> newSet = new HashSet<Key>();
newSet.add(entry.getKey());
map.put(entry.getId(), newSet);
}
}
ImmutableSetMultimap has a builder:
ImmutableSetMulitimap.Builder<Key, Value> builder = ImmutableSetMulitimap.builder();
for (Entry<Key, Value> entry : entries) {
builder.put(entry.getKey(), entry.getValue());
}
ImmutableSetMulitimap<Key, Value> map = builder.build();
For more info please see the javadoc

Search a HashMap in an ArrayList of HashMap

I have an ArrayList of HashMap. I want to search a HashMap in it but unable to find a way to achieve this. Please suggest me how it can be done?
Thanks.
Answer to your question the way i understood it!
for (HashMap<String, String> hashMap : yourArrayList)
{
// For each hashmap, iterate over it
for (Map.Entry<String, String> entry : hashMap.entrySet())
{
// Do something with your entrySet, for example get the key.
String sListName = entry.getKey();
}
}
Your Hashmap might use other types, this one uses Strings.
See if this helps:
#Test
public void searchMap() {
List<Map<String, String>> listOfMaps = new ArrayList<Map<String,String>>();
Map<String, String> map1 = new HashMap<String, String>();
map1.put("key1", "value1");
Map<String, String> map2 = new HashMap<String, String>();
map1.put("key2", "value2");
Map<String, String> map3 = new HashMap<String, String>();
map1.put("key3", "value3");
listOfMaps.add(map1);
listOfMaps.add(map2);
listOfMaps.add(map3);
String keyToSearch = "key2";
for (Map<String, String> map : listOfMaps) {
for (String key : map.keySet()) {
if (keyToSearch.equals(key)) {
System.out.println("Found : " + key + " / value : " + map.get(key));
}
}
}
}
Cheers!
Object myObj;
Object myKey;
//Traverse the list
for(HashMap curMap : listOfMaps){
//If this map has the object, that is the key doesn't return a null object
if( (myObj = curMap.get(myKey)) != null) {
//Stop traversing because we are done
break;
}
}
//Act on the object
if(myObj != null) {
//TODO: Do your logic here
}
If you are looking to get the reference to the Map instead of the object (for whatever reason) same process applies, except you just store the reference to the map:
Map myMap;
Object myKey;
//Traverse the list
for(HashMap curMap : listOfMaps){
//If this map has the object, that is the key doesn't return a null object
if(curMap.get(myKey) != null) {
//Store instance to the map
myMap = curMap;
//Stop traversing because we are done
break;
}
}
//Act on the map
if(myMap != null) {
//TODO: Do your logic here
}
Try below improved code for searching the key in a list of HashMap.
public static boolean searchInMap(String keyToSearch)
{
boolean returnVal = false;
List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
Map<String, String> map1 = new HashMap<String, String>();
map1.put("key1", "value1");
Map<String, String> map2 = new HashMap<String, String>();
map1.put("key2", "value2");
Map<String, String> map3 = new HashMap<String, String>();
map1.put("key3", "value3");
listOfMaps.add(map1);
listOfMaps.add(map2);
listOfMaps.add(map3);
for (Map<String, String> map : listOfMaps)
{
if(map.containsKey(keyToSearch))
{
returnVal =true;
break;
}
}
return returnVal;
}
The Efficient way i've used to search a hashmap in an arraylist without using loops. Since loop makes execution time longer
try{
int index = list.indexOf(map); // map is your map to find in ArrayList
if(index>=0){
HashMap<String, String> map = array_list.get(index);
// Here you can get your values
}
}
catch(Exception e){
e.printStackTrace();
Log.i("HashMap","Not Found");
}
if you have an ArrayList like this one: ArrayList<HashMap<String, String>>
and you want to compare one of the values inside the HashMap try this code.
I use it to compare settings of my alarm notifications.
for (HashMap<String, String> map : AlarmList) {
for (String key : map.keySet())
{
if (key.equals("SendungsID"))
{
if(map.get(key).equals(alarmMap.get("AlarmID")))
{
//found this value in ArrayList
}
}
}
}

Categories