Hashmap inside a hashmap with arraylist - java

Declaration:-
private static HashMap<String, HashMap<String, ArrayList>> parentMap = new HashMap<>();
private static HashMap<String, ArrayList> childMap = new HashMap<>();
How do I want to store data in hashmap?
"India":
"EmployeeName":[A,B,C]
"China":
"EmployeeName":[D,E,F]
Methods used:-
public static ArrayList<String> getMap(String parentkey, String childKey) {
return parentMap.get(parentkey).get(childKey);
}
public static ArrayList<String> setMap(String parentkey, String childKey, String value) {
childMap.computeIfAbsent(childKey, k -> new ArrayList<>()).add(value);
parentMap.put(parentkey, childMap);
return getMap(parentkey, childKey);
}
setMap("India", "EmployeeName", "A")
setMap("India", "EmployeeName", "B")
setMap("India", "EmployeeName", "C")
setMap("China", "EmployeeName", "D")
setMap("China", "EmployeeName", "E")
setMap("China", "EmployeeName", "F")
How data get stored and printed in hashmap while fetchng from getMap method:
System.out.println("India" + getMap("India").get("EmployeeName"));
System.out.println("China" + getMap("China").get("EmployeeName"));
"India" [A,B,C,D,E,F]
"China" [A,B,C,D,E,F]
Whilst i know keeping the childKey name unique would do thejob for me but I wish to keep the same childKey name under each parentkey name and store the respecive value in arraylist.
Any solution to my problem is welcome.

The problem is that you keep reusing the same childMap, regardless of which parentKey is being used. You need to look up the respective child map when adding values.
That means that childMap should be a local variable, nothing more. Delete your private static HashMap<String, ArrayList> childMap.
Try this:
public static ArrayList<String> setMap(String parentkey, String childKey, String value) {
HashMap<String, ArrayList> childMap = parentMap.computeIfAbsent(parentkey, k->new HashMap<>());
childMap.computeIfAbsent(childKey, k -> new ArrayList<>()).add(value);
return getMap(parentkey, childKey);
}
Proof that this works

Suggestion, don't have generic types and dont have static params
private HashMap<String, HashMap<String, ArrayList<String>>> parentMap = new HashMap<>();
private HashMap<String, ArrayList<String>> childMap = new HashMap<>();
Try to replace this method
public ArrayList<String> setMap(String parentkey, String childKey, String value) {
childMap.putIfAbsent(childKey, new ArrayList<>()); // inserts a key only if the key is not already present
childMap.get(childKey).add(value); // puts the value in the existing key and
if (!parentMap.containsKey(parentkey)) { // puts in the parent map only if not present.
parentMap.put(parentkey, childMap);
}
}
Since the childmap is referenced already, No need to put again.

If I was you I will do it in more "OOP way" so that you can benefit from static typing. Something like:
import java.util.List;
class Employee{
String name;
String getName(){
return name;
}
}
public class CompanyBranch{
String national;
List<Employee> employees;
List<String> getEmployeeAllName(){
return employees.stream().map(Employee::getName).toList();
}
}

Related

Extract and copy values from JSONObject to HashMap

I am having a JSON which contains upto 1000 Keys. I need some specific keys out of it.
Rather than traversing through the JSON and finding key and put its value in required parameter.
I thought of doing it in other way.
I am creating a HashMap of the keys I need.
Now i want to pass a JSONObject through it, where if we find the keys in JSONObject, it will automatically update the HashMap with the required keys.
Is there some function given by Spring where we can do it easily or do I Have to loop through it.
For Example:
JSONObject:-
{
"a":"a",
"b":"b",
"c":"c",
"d":"d",
"e":"e",
}
HashMap that I created :-
Map<String, Object> keys = new HashMap<>();
keys .put("a", "");
keys .put("b", "");
I want a function where i would pass two params
function HashMap mapJsonToHashMap(HashMap, JSONObject) {
}
Returned HashMap would be :-
{
"a":"a",
"b":"b"
}
IMO 1000 keys are not a big deal, so I would go for a simple solution of deserialize it to an object, then just filter/map using streams. Something like:
ObjectMapper objectMapper = new ObjectMapper();
Set<String> keys = new HashSet<>();
keys.add("key-1");
keys.add("key-3");
List<Parameter> list =
objectMapper.readValue("[{ \"key\":\"key-1\", \"value\":\"aaa\" }, { \"key\":\"key-2\", \"value\":\"bbb\" }, { \"key\":\"key-3\", \"value\":\"ccc\" }]", new TypeReference<List<Parameter>>(){});
List<Parameter> filteredList = list.stream()
.filter(l -> keys.contains(l.getKey()))
.collect(Collectors.toList());
// in case you really want to put results in a Map
Map<String, String> KeyValueMap = filteredList.stream()
.collect(Collectors.toMap(Parameter::getKey, Parameter::getValue));
public class Parameter
{
private String key;
private String value;
public String getKey()
{
return key;
}
public void setKey(String key)
{
this.key = key;
}
public String getValue()
{
return value;
}
public void setValue(String value)
{
this.value = value;
}
}
You can try something like this,
Convert JSON to HashMap
Then remove unwanted entries from the converted map
public HashMap mapJsonToHashMap(HashMap keys, JSONObject json) {
// Convert JSON to HashMap
ObjectMapper mapper = new ObjectMapper();
Map<String, String> jsonMap = mapper.readValue(json, Map.class);
// Iterate jsonMap and remove invalid keys
for(Iterator<Map.Entry<String, String>> it = jsonMap .entrySet().iterator();
it.hasNext(); ) {
Map.Entry<String, String> entry = it.next();
if(!keys.containsKey(entry.getKey())) {
it.remove();
}
}
return jsonMap;
}

How to check String equality while iterating over two lists?

I have two java classes:
public class MyClass1 {
private String userId;
private String userName;
private List<CustomList1> customList1;
// getters and setters
// inner CustomList1 class
}
public class MyClass2 {
private String userId;
private List<CustomList2> customList2;
// getters and setters
// inner CustomList2 class
}
Now, I have have lists of these classes:
List<MyClass1> classOneList;
List<MyClass2> classTwoList;
In both classOneList and classTwoList lists, object should be sorted with userId ascending. userId in both lists should have same values. What I want to check is that:
Has both lists same size? If not, thow error exception about.
Has every next element from both list the same userId? If not, throw another exception.
Step 1. I have done with simply if statement.
By prototype, step 2. should look like this:
for (el1, el2 : classOneList, classTwoList) {
el1.getUserId().isEqualTo(el2.getUserId());
}
Try the below code for your problem.
public class Testing {
public static void main(String[] args) {
Map<String, List<String>> map1 = new LinkedHashMap<String, List<String>>();
List<String> m1l1 = new LinkedList<String>();
m1l1.add("One");
m1l1.add("Two");
m1l1.add("Three");
m1l1.add("Four");
map1.put("1", m1l1);
List<String> m1l2 = new LinkedList<String>();
m1l2.add("One");
m1l2.add("Two");
m1l2.add("Three");
m1l2.add("Four");
map1.put("2", m1l2);
// Add more element into the map1 by creating more list.
Map<String, List<String>> map2 = new LinkedHashMap<String, List<String>>();
List<String> m2l1 = new LinkedList<String>();
m2l1.add("One");
m2l1.add("Two");
m2l1.add("Three");
m2l1.add("Four");
map2.put("1", m2l1);
// Add more element into the map2 by creating more list.
for (Entry<String, List<String>> entry : map1.entrySet()) {
if (map2.containsKey(entry.getKey())) {
if (entry.getValue().size() == map2.get(entry.getKey()).size()) {
} else {
System.out.println("UserId are same but list are different for userid: " + entry.getKey());
}
}
else {
System.out.println("Userid '"+entry.getKey()+"' exists in map1 but is not found in map2");
}
}
}
}
Hope this may help you.
if(classOneList.size() != classTwoList.size()){
throw new ErrorException();
}else{
classOneList = classOneList.stream().sorted(Comparator.comparing(MyClass1::getUserId)).collect(Collectors.toList());
classTwoList = classTwoList.stream().sorted(Comparator.comparing(MyClass2::getUserId)).collect(Collectors.toList());
for (int i = 0; i < classOneList.size(); i++){
if(!classOneList.get(i).getUserId().equals(classTwoList.get(i).getUserId())){
throw new AnotherErrorException();
}
}
}

How to substract hashmap data in java

I save my data in hashmap. I have two hashmap data, one from database and one from activity result. I want to do some equation with that data, but only if key in activity math with database key. I try to substract activity data with the database data, but the result is always 0.
Data from database and result activity is passed to this hashmap class:
public class PositionData implements Serializable {
private String name;
public HashMap<String, Integer> values;
public HashMap<String,String> routers;
public PositionData(String name) {
// TODO Auto-generated constructor stub
this.name=name;
values = new HashMap<String, Integer>();
routers = new HashMap<String, String>();
}
public void addValue(Router router,int strength){
values.put(router.getBSSID(), strength);
routers.put(router.getBSSID(),router.getSSID());
}
public String getName() {
return name;
}
public String toString() {
String result="";
result+=name+"\n";
for(Map.Entry<String, Integer> e: this.values.entrySet())
result+=routers.get(e.getKey())+" : "+e.getValue().toString()+"\n";
return result;
}
public HashMap<String, Integer> getValues() {
return values;
}
public HashMap<String, String> getRouters() {
return routers;
}
And this is how i do substraction in activity class:
PositionData positionData = (PositionData) intent
.getSerializableExtra("PositionData");
positionsData=db.getReadings(building);
HashMap<String, Integer> rssi = positionData.getValues();
HashMap<String, Integer> rssi1 = positionsData.get(0).getValues();
HashMap<String, String> dest = positionsData.get(0).getRouters();
int dista = 0;
if (positionData.equals(dest)){
dista = Integer.parseInt(String.valueOf(rssi))-Integer.parseInt(String.valueOf(rssi1));
}
Log.v("dis:", String.valueOf(dista));
I have data from class database and class result, both data is passed to HashMap activity to get positionData form. After i get the form, i calculate it in equation class. So, here i have 4 class.
I create generic example for you. I think that can help you understand how you can do equation on your hashmaps.
HashMap<String, Integer> activity= new HashMap<String, Integer>();
HashMap<String, Integer> database = new HashMap<String, Integer>();
Iterator iter = activity.keySet().iterator(); // getting iterator from keySet from one of hashmaps
// Iterate through one of hashmaps keys
while(iter.hasNext()){
String s = (String) iter.next();
if(database.containsKey(s)){ // finding key in second hashmap
// in here you can do your equation;
}
}
It appears that you are trying to compare the contents of a HashMap to object PositionData. You may have to override PositionData's .equals() method so it knows how to compare its contents to a HashMap. Maybe something like the following:
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o instanceof Map) {
Map m = (HashMap) o;
/* loop through both data structures and compare, return true if same */
}
/* compare two instances of PositionData */
return false;
Another option is to write a method to iterate through both and compare their contents, without the need of using/overriding .equals().

Pushing the resultset data onto a nested hashmap with a List

I'm trying to push my resultset data onto a nested map. Honestly, I've been struggling with the logic of how to do it. Here's a sample of my resultset data,
ID Main Sub
1 Root Carrots
2 Root Beets
3 Root Turnips
4 Leafy Spinach
5 Leafy Celery
6 Fruits Apples
7 Fruits Oranges
I created a hashmap HashMap<Integer, HashMap<String, List<String>>>, in which I thought the innermap could hold the main col as key and the corresponding subs as the list of values. The outermap would contain the id as the key and the corresponding map as the value. I'm struggling to achieve this.
Any help would be appreciated.
I would suggest using a different structure.
You have unique Id's and sub, but your Main can be duplicate.
Thus I would suggest using the following structure:
HashMap>
where POJO has ID and sub.
the key of map would be main.
Thus you can easily do:
if (map.get(main)==null){
List<POJO> pojoList= new List<>();
pojolist.add(pojo);
}else{
List<POJO> pojoList=map.get(main);
pojoList.add(pojo);
}
But it ultimately depends if you need to do lookup using ID or main.
Below is the answer to your question. But the question is probably wrong. Since the ID is unique (just a guess) you're probably looking for
Map<Integer, DataObject> map = new HashMap<>();
where DataObject is a POJO containing the variabels main and sub. Adding data to such a structure is easy.
Answer to question (added to show you how Maps and Lists work):
private Map<Integer, Map<String, List<String>>> map = new HashMap<>();
public static void main(String[] args) {
new Tester().go();
}
private void go() {
add(1, "Root", "Carrots");
add(2, "Root", "Beets");
add(3, "Root", "Turnips");
add(4, "Leafy", "Spinach");
add(5, "Leafy", "Celery");
add(6, "Fruits", "Apples");
add(7, "Fruits", "Oranges");
}
private void add(int id, String main, String sub) {
if (!map.containsKey(id)) {
map.put(id, new HashMap<String, List<String>>());
}
ArrayList<String> list = new ArrayList<String>();
list.add(sub);
map.get(id).put(main, list);
}
There is no need to make nested hash maps because each row in the example is unique (each List in nested map will have only one value).
In any case here is algorithm example in Java 8 style for your particular need :
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<ResultSet> rows = new ArrayList<>();
rows.add(new ResultSet().setId(1).setMain("Root").setSub("Carrots"));
rows.add(new ResultSet().setId(2).setMain("Root").setSub("Beets"));
rows.add(new ResultSet().setId(3).setMain("Root").setSub("Turnips"));
rows.add(new ResultSet().setId(4).setMain("Leafy").setSub("Spinach"));
rows.add(new ResultSet().setId(5).setMain("Leafy").setSub("Celery"));
rows.add(new ResultSet().setId(6).setMain("Fruits").setSub("Apples"));
rows.add(new ResultSet().setId(7).setMain("Fruits").setSub("Oranges"));
HashMap<Integer, HashMap<String, List<String>>> result = new HashMap<>();
rows.forEach(row -> {
HashMap<String, List<String>> subsByMain = result.getOrDefault(row.getId(), new HashMap<>());
List<String> subs = subsByMain.getOrDefault(row.getMain(), new ArrayList<>());
subs.add(row.getSub());
subsByMain.put(row.getMain(), subs);
result.put(row.getId(), subsByMain);
});
}
static class ResultSet {
private Integer id;
private String main;
private String sub;
Integer getId() {
return id;
}
ResultSet setId(Integer id) {
this.id = id;
return this;
}
String getMain() {
return main;
}
ResultSet setMain(String main) {
this.main = main;
return this;
}
String getSub() {
return sub;
}
ResultSet setSub(String sub) {
this.sub = sub;
return this;
}
}
}

How to properly lazy initialize Map of Map of Map?

It may be a bad practice, but I haven't been able to figure out any better solution for my problem. So I have this map
// Map<state, Map<transition, Map<property, value>>>
private Map<String, Map<String, Map<String, String>>> properties;
and I want to initialize it so I don't get NullPointerException with this
properties.get("a").get("b").get("c");
I tried this one but I didn't work (obviously)
properties = new HashMap<String, Map<String, Map<String,String>>>();
Other things I tried didn't compile.
Also if you have any ideas how to avoid this nested maps, I would appreciate it.
It seems to me that you need to create your own Key class:
public class Key {
private final String a;
private final String b;
private final String c;
public Key(String a, String b, String c) {
// initialize all fields here
}
// you need to implement equals and hashcode. Eclipse and IntelliJ can do that for you
}
If you implement your own key class, your map will look like this:
Map<Key, String> map = new HashMap<Key, String>();
And when looking for something in the map you can use:
map.get(new Key("a", "b", "c"));
The method above will not throw a NullPointerException.
Please remember that for this solution to work, you need to override equals and hashcode in the Key class. There is help here. If you don't override equals and hashcode, then a new key with the same elements won't match an existing key in the map.
There are other possible solutions but implementing your own key is a pretty clean one in my opinion. If you don't want to use the constructor you can initialize your key with a static method and use something like:
Key.build(a, b, c)
It is up to you.
You need to put maps in your maps in your map. Literally:
properties = new HashMap<String, Map<String, Map<String,String>>>();
properties.put("a", new HashMap<String, Map<String,String>>());
properites.get("a").put("b", new HashMap<String,String>());
If your target is lazy initialization without NPE you have to create your own map:
private static abstract class MyMap<K, V> extends HashMap<K, V> {
#Override
public V get(Object key) {
V val = super.get(key);
if (val == null && key instanceof K) {
put((K)key, val = create());
}
return val;
}
protected abstract V create();
}
public void initialize() {
properties = new MyMap<String, Map<String, Map<String, String>>>() {
#Override
protected Map<String, Map<String, String>> create() {
return new MyMap<String, Map<String, String>>() {
#Override
protected Map<String, String> create() {
return new HashMap<String, String>();
}
};
}
};
}
You could use a utility method:
public static <T> T get(Map<?, ?> properties, Object... keys) {
Map<?, ?> nestedMap = properties;
for (int i = 0; i < keys.length; i++) {
if (i == keys.length - 1) {
#SuppressWarnings("unchecked")
T value = (T) nestedMap.get(keys[i]);
return value;
} else {
nestedMap = (Map<?, ?>) nestedMap.get(keys[i]);
if(nestedMap == null) {
return null;
}
}
}
return null;
}
This can be invoked like this:
String result = get(properties, "a", "b", "c");
Note that care is required when using this as it is not type-safe.
The only way to do it with this structure is to pre-initialise the 1st and 2nd level maps with ALL possible keys. If this is not possible to do you can't achieve what you are asking with plain Maps.
As an alternative you can build a custom data structure that is more forgiving. For example a common trick is for a failed key lookup to return an "empty" structure rather than null, allowing nested access.
You can't initialize this in one go, since you normally don't know what keys you'll have in advance.
Thus you'd have to check whether the submap for a key is null and if so you might add an empty map for that. Preferably you'd only do that when adding entries to the map and upon retrieving entries you return null if one of the submaps in the path doesn't exist. You could wrap that in your own map implementation for ease of use.
As an alternative, apache commons collections' MultiKeyMap might provide what you want.
It's impossible to use properties.get("a").get("b").get("c"); and be sure to avoid null unless you make your own Map. In fact, you can't predict that your map will contains "b" key.
So try to make your own class to handle nested get.
I think a better solution is using an object as the only key to the map of values. The key will be composed of three fields, state, transition and property.
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
public class Key {
private String state;
private String transition;
private String property;
public Key(String state, String transition, String property) {
this.state = state;
this.transition = transition;
this.property = property;
}
#Override
public boolean equals(Object other) {
return EqualsBuilder.reflectionEquals(this, other);
}
#Override
public int hashCode() {
return HashCodeBuilder.reflectionHashCode(this);
}
}
When you check for a value, the map will return null for a key that is not associated with a value
Map<Key, String> values = new HashMap<Key, String>();
assert values.get(new Key("a", "b", "c")) == null;
values.put(new Key("a", "b", "c"), "value");
assert values.get(new Key("a", "b", "c")) != null;
assert values.get(new Key("a", "b", "c")).equals("value");
To efficiently and correctly use an object as a key in a Map you should override the methods equals() and hashCode(). I have built thos methods using the reflective functionalities of the Commons Lang library.
I think, following is the easier way:
public static final Map<Integer, Map<Integer, Map<Integer, Double>>> A_Map = new HashMap<Integer, Map<Integer, Map<Integer, Double>>>()
{
{
put(0, new HashMap<Integer, Map<Integer, Double>>()
{
{
put(0, new HashMap<Integer, Double>()
{
{
put(0, 1 / 60.0);
put(1, 1 / 3600.0);
}
});
put(1, new HashMap<Integer, Double>()
{
{
put(0, 1 / 160.0);
put(1, 1 / 13600.0);
}
});
}
});
put(1, new HashMap<Integer, Map<Integer, Double>>()
{
{
put(0, new HashMap<Integer, Double>()
{
{
put(0, 1 / 260.0);
put(1, 1 / 3600.0);
}
});
put(1, new HashMap<Integer, Double>()
{
{
put(0, 1 / 560.0);
put(1, 1 / 1300.0);
}
});
}
});
}
};
Using computeIfAbsent/putIfAbsent makes it simple:
private <T> void addValueToMap(String keyA, String keyB, String keyC, String value) {
map.computeIfAbsent(keyA, k -> new HashMap<>())
.computeIfAbsent(keyB, k -> new HashMap<>())
.putIfAbsent(keyC, value);
}

Categories