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());
Related
How can I convert a List<Map<String, Object>> to a <List<Map<String, String>>?
My Object values are Integer, String, and LocalDate.
Map<String, String> newMap = new HashMap<String, String>();
for (Map<String, Object> element: list) {
for (Entry<String, Object> entry : element.entrySet()) {
newMap.put(entry.getKey(), (String) entry.getValue());
}
}
This doesn't work for me.
Updated
Thanks guys in comments for help!
Wanna post here full algorythm, maybe it can be usefull for someone
// data preparing
LocalDate date = LocalDate.now();
Map<String, Object> map1 = new HashMap<>();
map1.put("key1", 4);
Map<String, Object> map2 = new HashMap<>();
map2.put("key2", date);
List<Map<String, Object>> subject = new ArrayList<>();
subject.add(0, map1);
subject.add(1, map2);
System.out.println(subject);
Map<String, String> newMap = new HashMap<>();
List<Map<String,String>> newList = new ArrayList<>();
for (Map<String, Object> element : subject) {
for (Map.Entry<String, Object> entry : element.entrySet()) {
newMap.put(entry.getKey(), String.valueOf(entry.getValue()));
newList.add(newMap);
}
}
//test results
System.out.println("----------------------------");
System.out.println(newList.get(0).get("key1").getClass());
System.out.println(newList.get(1).get("key2").getClass());
System.out.println(newList);
Just replace (String) entry.getValue() for String.valueOf, like that:
Map<String, String> newMap = new HashMap<String, String>();
for (Map<String, Object> element: list) {
for (Entry<String, Object> entry : element.entrySet()) {
newMap.put(entry.getKey(), String.valueOf(entry.getValue()));
}
}
A more functional approach to this would be:
private List<Map<String, String>> retypeFunctional(List<Map<String, Object>> list) {
List<Map<String, String>> result = list.stream()
.map(map -> map.entrySet().stream()
.collect(Collectors.toMap(Entry::getKey, e -> String.valueOf(e.getValue()))))
.collect(Collectors.toList());
return result;
}
Remember to:
import java.util.Map.Entry;
among other more obvious imports.
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?
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());
}
}
If I have this:
RequestBody formBody = new FormEncodingBuilder()
.add("email", "Jurassic#Park.com")
.add("tel", "90301171XX")
.build();
But instead of adding key value pairs individually, I just want to add a variable of type map that has a variable size, how do I go about adding it?
How about just iterating over the map yourself and adding each key/value? Example:
private FormEncodingBuilder makeBuilderFromMap(final Map<String, String> map) {
FormEncodingBuilder formBody = new FormEncodingBuilder();
for (final Map.Entry<String, String> entrySet : map.entrySet()) {
formBody.add(entrySet.getKey(), entrySet.getValue());
}
return formBody;
}
usage:
RequestBody body = makeBuilderFromMap(map)
.otherBuilderStuff()
.otherBuilderStuff()
.otherBuilderStuff()
.build();
If you do the typing correctly the code provided by nbokmans works well. Here the corrected version:
private RequestBody makeFormBody(final Map<String, String> map) {
FormEncodingBuilder formBody = new FormEncodingBuilder();
for (final Map.Entry<String, String> entrySet : map.entrySet()) {
formBody.add(entrySet.getKey(), entrySet.getValue());
}
return formBody.build();
}
I have map of <String, Object>:
params={
dateOfBirthTo=23.05.2013,
lastName=bbb, ssn=aa-ccc-ddd,
gender=MALE,
dateOfBirthFrom=03.05.2013,
firstName=aaa
}
Then I have form which contains variable from this map. How I can create new form with this value through reflection?
Something like:
SimpleForm form = new SimpleForm();
Map<String, Object> parameters = request.getParams();
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
// fill form
}
You could use Apache Commons BeanUtils
SimpleForm form = new SimpleForm();
Map<String, Object> parameters = request.getParams();
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
BeanUtils.setProperty(form, entry.getKey(), entry.getValue());
}