i have the following data:
how can i get the key if i put the value to as argument?
Test1(stringtest2Map={de=Test2(name=aa, stringStringMap={alex=sven, serdar=alo})})
for example if internalName= "alo" then it should returns serdar if = "sven" then should returns alex.
my try:
Test2 test2 = new Test2();
test2.name = "aa";
Map<String, String> map = new HashMap<>();
map.put("alex", "sven");
map.put("serdar", "alo");
test2.stringStringMap = map;
Test1 test1 = new Test1();
Map<String, Test2> map1 = new HashMap<>();
map1.put("de", test2);
test1.stringtest2Map = map1;
System.out.println(test1.toString());
String internalName = "alo";
String firstName =
test1.stringtest2Map.values().stream()
.map(e -> e.stringStringMap.get(internalName))
.findFirst()
.orElse(null);
System.out.println(firstName);
public class Test1 {
public Map<String, Test2> stringtest2Map;
}
public class Test2 {
public String name;
public Map<String, String> stringStringMap;
}
but it does not work.
First of all, having to do such lookup on Maps means that you may need to consider alternate data structure for saving your data. Still, here are possible solutions to obtain the results you are expecting.
1.
Optional<Optional<String>> firstName =
test1.stringtest2Map.values().stream()
.map(e -> e.stringStringMap.entrySet().stream()
.filter(stringStringEntry -> stringStringEntry.getValue().equals(internalName))
.findFirst()
.map(Map.Entry::getKey))
.findFirst();
firstName.ifPresent(System.out::println);
String firstName = null;
for(Test2 t2 : test1.stringtest2Map.values()) {
for(Map.Entry<String, String> keyValue : t2.stringStringMap.entrySet()) {
if(keyValue.getValue().equals(internalName)) {
firstName = keyValue.getKey();
break;
}
}
}
if(firstName != null) {
System.out.println(firstName);
}