Convert from for each to stream in java lambda - java

I have the below expression
Map<String, String> institutionList = new LinkedHashMap<String, String>();
institutionService.list().forEach(institution -> institutionList.put(institution.getCode(),institution.getName()));
I tried like below.
institutionService.list().stream().collect(Collectors.toMap(‌​Institution::getCode‌​, Institution::getName));
But still error. how to convert this into stream() & map() with lambda?

An example which is working just fine:
Map<String, String> p = new HashMap<String, String>();
List<String> values = new ArrayList<String>(Arrays.asList("2", "4", "1"));
p = values.stream().collect(Collectors.toMap(String::toString, String::toString));
System.out.println(p);
results in
{1=1, 2=2, 4=4}
If we transfer it to your problem, the code might look like this:
I have the below expression
Map<String, String> institutionList = new LinkedHashMap<String, String>();
institutionList = institutionService.list().stream().collect(Collectors.toMap(‌​Institution::getCode‌​, Institution::getName));
In this case, I assume that your service gives values of class Institution

Related

Java append `HashMap` values to existing HashMap if key matches

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.

am getting the Type mismatch: cannot convert from element type Object to String

I am storing the zero value at specific date.
I am getting the exception at dur_call.put(value, "0")
HashMap<String, String> dur_call = new HashMap<String, String>();
HashMap<String, String> brows_call = new HashMap<String, String>();
HashMap<String, String> brows_call_dst = new HashMap<String, String>();
HashMap<String, String> subs = new HashMap<String, String>();
HashMap<String, String> sub_dur = new HashMap<String, String>();
HashMap<String, String> act = new HashMap<String, String>();
HashMap<String, String> low_bal = new HashMap<String, String>();
HashMap<String, String> deact = new HashMap<String, String>();
HashMap<String, String> re_act = new HashMap<String, String>();
for (String value : datetime) {
dur_call.put(value, "0");
brows_call.put(value, "0");
brows_call_dst.put(value, "0");
subs.put(value, "0");
sub_dur.put(value, "0");
act.put(value, "0");
low_bal.put(value, "0");
deact.put(value, "0");
re_act.put(value, "0");
}
I am sure that you get the error one line above, at
for (String value : datetime) {
That is the only place, where something wants to be converted into a String.
What is the type of variable datetime ? It seems to me that datetime is not an Iterable of Strings, which it should be (for that code to work).
Is your error an exception at runtime or a compiler error?
If it is an exception and datetime is an iterable of Strings, then you mixed up generics with some untyped Collection access - your compiler will probably give you a warning, where this occurs in your code - or you have annotated that place with a #SuppressWarnings("unchecked")
(See also What is SuppressWarnings (“unchecked”) in Java?)
In this case try to make your whole code working without the unchecked warning and without the suppression of it.
If your error is a compiler error, you need to change the key of all your Maps to the type of the datetime iterable. java.util.Date maybe?

Using Java 8 streams groupingBy on a list of list of maps?

From the following input
[
[{group=a, value=cat}, {group=b, value=dog}],
[{group=a, value=cow}, {group=b, value=bat}]
]
how do I get the following output
{
a=[{value=cat}, {value=cow}],
b=[{value=dog}, {value=bat}]
}
using Java 8 streams?
I have the following standard solution
Map<String, String > map1 = new LinkedHashMap<>();
map1.put("group", "a");
map1.put("value", "cat");
Map<String, String > map2 = new LinkedHashMap<>();
map2.put("group", "b");
map2.put("value", "dog");
Map<String, String > map3 = new LinkedHashMap<>();
map3.put("group", "a");
map3.put("value", "cow");
Map<String, String > map4 = new LinkedHashMap<>();
map4.put("group", "b");
map4.put("value", "bat");
List<Map<String, String>> list1 = Arrays.asList(map1, map2);
List<Map<String, String>> list2 = Arrays.asList(map3, map4);
List<List<Map<String, String>>> input = Arrays.asList(list1, list2);
Map<String, List<Map<String, String>>> output = new LinkedHashMap<>();
for (List<Map<String, String>> list : input) {
for (Map<String, String> map : list) {
String group = map.get("group");
if (!output.containsKey(group)) {
output.put(group, new ArrayList<>());
}
List<Map<String, String>> values = output.get(group);
values.add(map);
}
}
I saw that there is a Collectors.groupingBy method, but I couldn't figure out how to use it.
Map<String, List<Map<String, String>>> output = input.stream()
.<am I missing out some steps here?>
.collect(Collectors.groupingBy(<what goes here?>))
To generate the same output you should flatten list of lists to the single list via flatMap before grouping:
output = input.stream().flatMap(List::stream)
.collect(Collectors.groupingBy(map -> map.get("group")));
This code generates the same output like the imperative code you've posted:
{
a=[{group=a, value=cat}, {group=a, value=cow}],
b=[{group=b, value=dog}, {group=b, value=bat}]
}
Note however that it differs from your desired output. To get the desired output you may need to specify downstream collector:
output = input.stream()
.flatMap(List::stream)
.collect(Collectors.groupingBy(map -> map.get("group"),
Collectors.mapping(
map -> Collections.singletonMap("value", map.get("value")),
Collectors.toList())));
Now the result is
{
a=[{value=cat}, {value=cow}],
b=[{value=dog}, {value=bat}]
}

how do i write this as a list<map<string, string> structure in java

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> >

Filling Map - java

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>();

Categories