Is anyone able to provide me with a better way than the below for converting a Java Map object to a Properties object?
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("key", "value");
Properties properties = new Properties();
for (Map.Entry<String, String> entry : map.entrySet()) {
properties.put(entry.getKey(), entry.getValue());
}
Thanks
Use Properties::putAll(Map<String,String>) method:
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("key", "value");
Properties properties = new Properties();
properties.putAll(map);
you also can use apache commons-collection4
org.apache.commons.collections4.MapUtils#toProperties(Map<K, V>)
example:
Map<String, String> map = new LinkedHashMap<String, String>();
map.put("name", "feilong");
map.put("age", "18");
map.put("country", "china");
Properties properties = org.apache.commons.collections4.MapUtils.toProperties(map);
see javadoc
https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/MapUtils.html#toProperties(java.util.Map)
You can do this with Commons Configuration:
Properties props = ConfigurationConverter.getProperties(new MapConfiguration(map));
http://commons.apache.org/configuration
Try MapAsProperties from Cactoos:
import org.cactoos.list.MapAsProperties;
import org.cactoos.list.MapEntry;
Properties pros = new MapAsProperties(
new MapEntry<>("foo", "hello, world!")
new MapEntry<>("bar", "bye, bye!")
);
I got the idea from this article but I modified to convert from a Map to Properties. This is needed if you may need to manipulate the inputs.
Map<String,String> input = System.getenv();
Properties output = input.entrySet().stream().collect(
Collectors.toMap(
e -> String.valueOf(e.getKey()),
e -> String.valueOf(e.getValue()),
(prev, next) -> next, Properties::new
)
);
Also if you want to filter values from the Map.
Map<String,String> input = System.getenv();
Properties output = input.entrySet()
.stream().filter(e -> e.getKey().startsWith("XYZ")).collect(
Collectors.toMap(
e -> String.valueOf(e.getKey()),
e -> String.valueOf(e.getValue()),
(prev, next) -> next, Properties::new
)
);
Related
Hello fellow developers,
Need your expertise on below problem
I have a below incoming list of maps
Map<String, Object> m1 = new HashMap<String, Object>();
m1.put("name", "alex");
m1.put("age", "40");
l1.add(m1);
m1 = new HashMap<String, Object>();
m1.put("name", "alex");
m1.put("state", "Texas");
l1.add(m1);
m1 = new HashMap<String, Object>();
m1.put("name", "alice");
m1.put("age", "35");
l1.add(m1);
m1 = new HashMap<String, Object>();
m1.put("name", "alice");
m1.put("state", "Arizona");
l1.add(m1);
m1 = new HashMap<String, Object>();
m1.put("name", "bob");
m1.put("age", "25");
l1.add(m1);
m1 = new HashMap<String, Object>();
m1.put("name", "bob");
m1.put("state", "Utah");
l1.add(m1);
I want the output list of map as below using java 8 streams-
[{name="alex", age="40", state="Texas"}
{name="alice", age="35", state="Arizona"}
{name="bob", age="25", state="Utah"}]
Appreciate any help here.
You can use toMap() collector with merge function.
l1.stream()
.collect(Collectors.toMap(m -> m.get("name").toString(), Function.identity(),
(map1, map2) -> { map1.putAll(map2); return map1;})
)
.values();
Indeed in this solution, we merge maps based on name key value. so if two maps have the same value for name key then they will merge.
since toMap() collector's result is Map<String,Map<String,Object>> here and desire result is Map<String,Object> so we have called values()
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 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
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());
}
how do i write this as a list structure in java
In this case i want the structure to be like this, Where options is also a key in another
hashmap called styles
options[{"value":"0","label":"zero"},{"value":"1","label":"one"},
{"value":"2","label":"two"}]
Here if i want to access options[1].value should give me 1 and options[2].label should give me two.
How can i achieve this with
LIst<Map<string><string[]>>?
Also Can i pass "options" array as one of the keys in my hash map
protected Map<String, String[]> getValueProperties(int view, Field field) {
Map<String, String> properties = new HashMap<String,String[]>();
properties.put("options", []);
return properties
}
I am new to handling data in this format, any pointers will be good
I think this can do:
List<Map<String,String>> options = new ArrayList<Map<String,String>>();
and populate as :
Map<String, String> option1 = new HashMap<String, String>();
option1.put("value", "0");
option1.put("level", "zero");
options.add(option1);
Map<String, String> option2 = new HashMap<String, String>();
option2.put("value", "1");
option2.put("level", "one");
options.add(option2);
Map<String, String> option3 = new HashMap<String, String>();
option3.put("value", "2");
option3.put("level", "two");
options.add(option3);
EDIT: You can populate the list in a loop as below:
List<Map<String,String>> options = new ArrayList<Map<String,String>>();
String[] levels = {"zero", "one", "two"};
for(int indx = 0; indx <levels.length; indx++){
Map<String, String> option = new HashMap<String, String>();
option.put("value", String.valueOf(indx));
option.put("level", levels[indx]);
options.add(option);
}
Use this data structure:
List< Map<String, String> >