How to substract hashmap data in java - 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().

Related

Hashmap inside a hashmap with arraylist

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

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

Sorting ArrayList of HashMap based on key value

I have a list of HashMaps. Each HashMap consists of several kay-value pairs and everything comes as a string. I am storing all the hashmaps inside an arraylist. Now I need to sort the arraylist based on the key inside the hashmap.
Here is my sample data:
{
"productID":"5643",
"productName":"Apple - iPod touch",
"outsidePrice":"189.99",
"merchantID":"134439",
"ourPrice":"184.99",
"storeName":"Ebay",
}
{
"productID":"3243",
"productName":"Apple - iPad",
"outsidePrice":"389.99",
"merchantID":"54439",
"ourPrice":"384.99",
"storeName":"Apple",
}
I am storing this data inside this structure.
ArrayList<HashMap<String, String>> data_list = new ArrayList<HashMap<String, String>>();
I have a huge list of items like this. Now I need to sort the arraylist based on the productName, Price, storeName, productID fields inside the hashmap.
I recommend that you use a custom product class to do this for you. It will ultimately make your code easier to maintain and more robust, IMHO.
How about this?
A class to represent your data:
class Product{
public string productId;
public string productName;
public BigDecimal outsidePrice;
public int merchantId;
public BigDecimal ourPrice;
public string storeName;
// whatever constuctors you need
}
A List of your products:
List<Product> products;
Now define a Comparator to sort, one for each field that you need to sort on. Here is an example for productId.
public class ProductProductIdComparator implements Comparator<Product>{
#Override
public int compare(Product product1, Product product2) {
if (product1.productId > product2.productId){
return +1;
}else if (product1.productId < product2.productId){
return -1;
}else{
return 0;
}
}
}
And finally, a Collections sort which accepts a comparator as an argument:
Collections.sort(products, new ProductProductIdComparator());
The Collections class provides a utility method for sorting a list in place, using a Comparator.
final List<Map<String, String>> dataList = new ArrayList<HashMap<String, String>>(4);
Collections.sort(dataList, new Comparator<Map<String, String>>() {
#Override
public int compare(final Map<String, String> map1, final Map<String, String> map2) {
// Get fields from maps, compare
}
}
You can use arrays.sort() to achieve this in short, at some minor memory cost.
HashMap[] result = Arrays.sort(list.toArray(), new Comparator() {
public void compare(Object o1, Object o2) {
HashMap<String, String> a = (HashMap<String, String>)o1;
HashMap<String, String> b = (HashMap<String, String>)o2;
// return value as per contract of Comparator.compare() doing whatever comparisons you need.
}
public boolean equals(Object obj) { return this == obj; }
});

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

Need help with java map and javabean

I have a nested map:
Map<Integer, Map<Integer, Double>> areaPrices = new HashMap<Integer, Map<Integer, Double>>();
and this map is populated using the code:
while(oResult.next())
{
Integer areaCode = new Integer(oResult.getString("AREA_CODE"));
Map<Integer, Double> zonePrices = areaPrices.get(areaCode);
if(zonePrices==null)
{
zonePrices = new HashMap<Integer, Double>();
areaPrices.put(areaCode, zonePrices);
}
Integer zoneCode = new Integer(oResult.getString("ZONE_CODE"));
Double value = new Double(oResult.getString("ZONE_VALUE"));
zonePrices.put(zoneCode, value);
myBean.setZoneValues(areaPrices);
}
I want to use the value of this Map in another method of the same class. For that I have a bean.
How do I populate it on the bean, so that I can get the ZONE_VALUE in this other method
In my bean I added one new field as:
private Map<Integer, Map<Integer, Double>> zoneValues;
with getter and setter as:
public Map<Integer, Map<Integer, Double>> getZoneValues() {
return zoneValues;
}
public void setZoneValues(Map<Integer, Map<Integer, Double>> areaPrices) {
this.zoneValues = areaPrices;
}
What I am looking for to do in the other method is something like this:
Double value = myBean.get(areaCode).get(zoneCode);
How do I make it happen :(
I would like to suggest a different, hopefully more readable solution:
public class PriceMap {
private Map<Integer, Map<Integer, Double>> priceMap =
new HashMap<Integer, Map<Integer, Double>>();
// You'd use this method in your init
public Double setPrice(Integer areaCode, Integer zoneCode, Double price) {
if (!priceMap.containsKey(zoneCode)) {
priceMap.put(zoneCode, new HashMap<Integer, Double>());
}
Map<Integer, Double> areaMap = priceMap.get(zoneCode);
areaMap.put(areaCode, price);
}
public void getPrice(Integer areaCode, Integer zoneCode) {
if (!priceMap.containsKey(zoneCode)) {
// Eek! Exception or return null?
}
Map<Integer, Double> areaMap = priceMap.get(zoneCode);
return areaMap.get(areaCode);
}
}
I think this is a better, more readable abstraction which, very importantly, makes it easier for you or someone else to read after a few months.
EDIT Added get get
If you're stuck with a get(areaCode).get(zoneCode) (order reversed), but myBean is entirely yours, you could do something like:
public class MyBean {
// I suppose you have this already
private final Map<Integer, Map<Integer, Double>> priceMap =
new HashMap<Integer, Map<Integer, Double>>();
private class LooksLikeAMap implements Map<Integer, Double> {
private Integer areaCode = areaCode;
public LooksLikeAMap(Integer areaCode) {
this.areaCode = areaCode;
}
public Double get(Object zoneCode) {
if (!priceMap.containsKey(zoneCode)) {
// Eek! Exception or return null?
}
Map<Integer, Double> areaMap = priceMap.get(zoneCode);
return areaMap.get(areaCode);
}
// Implement other methods similarly
}
public Map<Integer, Double> get(Integer areaCode) {
return new LooksLikeAMap(areaCode);
}
}
OK, programming in a HTML textarea is not my strong suit, but the idea is clear.
Make some Map like structure backed by the complete data set, and initialize that
Map structure with the required AreaCode.
If the idea is not clear, post a comment fast as it's late here:)
EDIT
I am an idiot. I thought the data was zone first, then area while the get should be area first, then zone. In this case the Map already has the right structure, first area then zone, so this is not necessary. The get-get is by default if you make
public MyBean {
public Map<Integer, Double> get(Integer areaCode) {
return data.get(areaCode);
}
}
To start with, all you need is
myBean.getZoneValues(areaCode).get(zoneCode);
the while loop has an annoyance, you need to call myBean.setZoneValues(areaPrices);
out side the while loop
You can't directly control the second get() call because you have a nested Map, you'll need to return the appropriate nested Map to be able to do what you want. A getter like this should do it:
public Map<Integer, Double> get(Integer areaCode) {
return zoneValues.get(areaCode);
}
So when the client code calls get(areaCode) a map will be returned that they can then call get(zoneCode) on.
I'd suggest that you refactor to eliminate the nested Maps though, because you can't stop client code from changing the returned Map, the code is tough to read and you'll have problems if you want to add any more functionality - imagine that you want to provide a String description of an area code in future.
Something like a Map<Integer, AreaCode> where AreaCode is an object that contains what you currently have as a nested Map might be a good place to start.

Categories