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()
Related
I have below HashMap(to.String()) printed below.
HashMap<String, HashMap<String, HashMap<String, Integer>>> abc = new HashMap<>();
HashMap abc = {disabled={account={testConfiguration=1, iterate=1}}}
I want to append {group={iterate=1}} to existing map if key disabled matches.
Finally my map should look like below, how can I achieve it?
HashMap abc = {disabled={account={testConfiguration=1, iterate=1}, {group={iterate=1}}}
I think you want this:
abc.computeIfPresent("disabled", (k,v) -> {
v.put("group", yourValue);
return v;
});
or simply:
if (abc.containsKey("disabled")) {
abc.get("disabled").put("group", yourValue);
}
I personally prefer the first approach, since it's a bit faster and works properly with concurrent maps.
Here is the example for your desired output
disabled={account={testConfiguration=1, iterate=1}, group={iterate=1}}
HashMap<String, Integer> accountmap = new HashMap<>();
HashMap<String, Integer> groupMap = new HashMap<>();
HashMap<String, HashMap<String, Integer>> disableMap = new HashMap<>();
HashMap<String, HashMap<String, HashMap<String, Integer>>> abc = new HashMap<>();
accountmap.put("testConfiguration",1);
accountmap.put("iterate",1);
disableMap.put("account",accountmap);
abc.put("disabled", disableMap);
if(abc.containsKey("disabled")){
groupMap.put("iterate", 1);
disableMap.put("group",groupMap);
}
System.out.println(abc.entrySet());
The below code gives you the hashmap in the following format
{disabled={account={testConfiguration=1, iterate=1}, group={iterate=1}}}
public static void main(String []args) {
HashMap<String, HashMap<String, HashMap<String, Integer>>> abc = new HashMap<>();
// HashMap abc = {disabled={account={testConfiguration=1, iterate=1}}}
HashMap<String, Integer> thirdHash = new HashMap<>();
thirdHash.put("testConfiguration", 1);
thirdHash.put("iterate", 1);
HashMap<String, HashMap<String, Integer>> secondHash = new HashMap<>();
secondHash.put("account", thirdHash);
abc.put("disabled", secondHash);
// append {group={iterate=1}}
HashMap<String, Integer> appendFirst = new HashMap();
appendFirst.put("iterate", 1);
if (abc.containsKey("disabled")) {
abc.get("disabled").put("group", appendFirst);
}
System.out.println(abc);
}
Happy Coding.
I'm in a little trouble building a hashmap but it took me a lot of time and I don't have a lot of experience with this kind of objects, my problem is when building the next hashmap:
Map<String, Map<String, Map<String, Object>>> map = new HashMap<String, Map<String, Map<String, Object>>>();
Map<String, Map<String, Object>> map1 = new HashMap<String, Map<String, Object>>();
Map<String, Object> map2 = new HashMap<String, Object>();
Map<String, Object> map3 = new HashMap<String, Object>();
map2.put("one",1);
map1.put("two", map2);
map.put("cero", map1);
System.out.println(map);
The output is:
{cero={two={one=1}}}
But now I want to add another key percent with string value 10 at cero key level like:
{percent=10,cero={two={one=1}}}
I tried something like:
Map<String, Object> map3 = new HashMap<String, Object>();
map3.put("percent", "10");
map.get("cero").putAll(map3);
There is an error in putAll method 'cause java needs a Map<String, Map<String, Object>> kind of object but I only need to add that percent property. Hope I'm clear with my question and you guys can help me, thanks.
We can try to add map1 to map3
Map<String, Map<String, Map<String, Object>>> map = new HashMap<String,
Map<String, Map<String, Object>>>();
Map<String, Map<String, Object>> map1 = new HashMap<String, Map<String, Object>>
();
Map<String, Object> map2 = new HashMap<String, Object>();
Map<String, Object> map3 = new HashMap<String, Object>();
map2.put("one",1);
map1.put("two", map2);
map3.put("percent", "10");
map3.put("cero",map1);
System.out.println(map3);
This gives following structure in map3
{percent=10,cero={two={one=1}}}
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> >
I have problem with filling a Map in Java, I think this is simple, but I can't resolve this.
Let's look at this:
Map<Integer, HashMap<String, String>> lineArrayData = new HashMap<Integer, HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
String singleData[];
int lineCounter = 0;
for ( String line : this.lines )
{
singleData = line.split("\\|\\|");
map.put("type", singleData[0]);
map.put("text", singleData[1]);
map.put("page", singleData[2]);
map.put("x", singleData[3]);
map.put("y", singleData[4]);
lineArrayData.put(lineCounter, map);
lineCounter++;
}
System.out.println(lineArrayData);
I have input
barcode||testowy test||1||100||100
text||texttstdasd||2||500||300
and my output is:
{0={text=texttstdasd, page=2, type=text, y=300, x=500}, 1={text=texttstdasd, page=2, type=text, y=300, x=500}}
what have I done wrong?
Move the following line inside the loop:
HashMap<String, String> map = new HashMap<String, String>();
Otherwise every iteration modifies the same inner map. The end result is that the outer map contains multiple references to the same inner map.
Here is the corrected version:
for ( String line : this.lines )
{
HashMap<String, String> map = new HashMap<String, String>();
singleData = line.split("\\|\\|");
...
Declare HashMap<String, String> map = new HashMap<String, String>(); inside the for loop.
You are using the same instance of the map in the loop. Also that should be
Map<Integer, Map<String, String>> lineArrayData = new HashMap<Integer, HashMap<String, String>>();
Map<String, String> map = new HashMap<String, String>();
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
)
);