I need to fill map with Iterable<Map.Entry>. The following is an original java code:
Iterable<Map.Entry<String, String>> conf;
Iterator<Map.Entry<String, String>> itr = conf.iterator();
Map<String, String> map = new HashMap<String, String>();
while (itr.hasNext()) {
Entry<String, String> kv = itr.next();
map.put(kv.getKey(), kv.getValue());
}
I have to rewrite it in groovy. Is there a concise groovy-way to do it?
I'd use collectEntries for that. It's similar to collect, but it's purpose is to create a Map.
def sourceMap = ["key1": "value1", "key2": "value2"]
Iterable<Map.Entry<String, String>> conf = sourceMap.entrySet()
def map = conf.collectEntries {
[(it.key): it.value]
}
Note the round braces around it.key that allow you to use a variable reference as key of the newly generated Entry.
In Groovy you can use the each closure instead of Iterator as follows
Map<Map.Entry<String, String>> sourceMap = ["key1" : "value1", "key2" : "value2"]
Map<Map.Entry<String, String>> targetMap = [:]
sourceMap.each{ key, value ->
targetMap[key] = value
}
println targetMap
Working example here : https://groovyconsole.appspot.com/script/5100319096700928
Related
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 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());
I am trying to retrieve a list of objects from a Stored Procedure in Oracle SQL. May you know how can I get an Arraylist from the code below?
ArrayList<String> strings = new ArrayList<>();
SimpleJdbcCall jdbcCall = new SimpleJdbcCall(dataSource).withProcedureName("P_ROUTES");
SqlParameterSource in = new MapSqlParameterSource()
.addValue("V_FIXED_INT", period)
.addValue("V_CARRIER", carrier)
.addValue("V_DATE_RANGE_START", dateRangeStart)
.addValue("V_DATE_RANGE_END", dateRangeEnd);
Map<String, Object> out = jdbcCall.execute(in);
ArrayList obj = (ArrayList) out.get("RET_CURSOR");
Map<String, Object> map = (Map<String, Object>) obj.get(0);
In map object I have the list of key - value pairs.
Check image below:
I am not sure that is the best solution but it works for me. I ll try to find something better. If you have any other suggestion feel free!
Map<String, Object> out = jdbcCall.execute(in);
ArrayList obj = (ArrayList) out.get("RET_CURSOR");
logger.info("Length of retrieved routes from database = " + obj.size());
for (Object o : obj) {
Map<String, Object> map = (Map<String, Object>) o;
for (Map.Entry<String, Object> entry : map.entrySet())
routes.add(entry.getValue().toString());
}
I'm looking for good way or complete API to create a hierarchical JSON from plain java.util.Properties object.
Exist java.util.Properties object, e.g.:
car.color=blue
car.places=4
car.motor.dimension=2L
car.motor.ps=120
and the target json structur should be:
{
"car":
{"color":"blue",
"places":4,
"motor":
{"dimension":"2L",
"ps":120
}
}
}
public void run() throws IOException {
Properties properties = ...;
Map<String, Object> map = new TreeMap<>();
for (Object key : properties.keySet()) {
List<String> keyList = Arrays.asList(((String) key).split("\\."));
Map<String, Object> valueMap = createTree(keyList, map);
String value = properties.getProperty((String) key);
value = StringEscapeUtils.unescapeHtml(value);
valueMap.put(keyList.get(keyList.size() - 1), value);
}
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(map);
System.out.println("Ready, converts " + properties.size() + " entries.");
}
#SuppressWarnings("unchecked")
private Map<String, Object> createTree(List<String> keys, Map<String, Object> map) {
Map<String, Object> valueMap = (Map<String, Object>) map.get(keys.get(0));
if (valueMap == null) {
valueMap = new HashMap<String, Object>();
}
map.put(keys.get(0), valueMap);
Map<String, Object> out = valueMap;
if (keys.size() > 2) {
out = createTree(keys.subList(1, keys.size()), valueMap);
}
return out;
}
The following project 'Java Properties to JSON' achieves exactly what you seek.
However, it has a restriction on Java 8.
Would be great if someone actually provides changes to make it Java 7 compatible.
You will need to parse your properties to Map<String, Object> where your Object will be either another Map<String, Object> or a String. For this you will have to write your own code. I suppose you will need to take your properties keys and split them over "." using method String.split(). Note that in your code you will need to use "\\." as a parameter as "." is a regular expression. Once you build your Map it is very easy to convert it to JSON using Jackson library or any available JSON library.
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