How to set value of HashMap in Model class - java

I want to set the values of georgiaHash and marylandHash into Key_journal_model class. That model class only contains these 2 hashmaps and their getter setter methods.
I tried with object but thats not working.
demoHash is a method which returns hashmap.
public class Hash_function {
public ArrayList<Key_journal_model> setHashmaps() {
ArrayList<Key_journal_model> kjmList = new ArrayList<Key_journal_model>();
HashMap<String, Float> georgiaHash = demoHash();
HashMap<String, Float> marylandHash = demoHash();
Key_journal_model kjm = new Key_journal_model(georgiaHash,marylandHash);
kjmList.add(kjm);
return kjmList;
}

Related

Copy fields and value of an object to a Map

I want to copy fields from a complex object- that is an object which contains other objects.
Now it copies wrapper classes with no issue but how do i copy the fields and values of the subclass
code
public Map<String, Object> getValueMapFromInsuranceVehicle(Long insuranceId) throws InvocationTargetException, IllegalAccessException {
InsurancePolicy insurance = repository.findById(insuranceId).get();
Method[] methods = insurance.getInsuranceVehicle().getClass().getMethods();
Map<String, Object> map = new HashMap<String, Object>();
for (Method m : methods) {
if (m.getName().startsWith("get")) {
Object value = m.invoke(insurance.getInsuranceVehicle());
map.put(m.getName().substring(3), value);
}
}
// add other fields specific to our needs like currentYear
return map;
}
From the code above it copies insuranceVehicle fields correctly, But i would like to copy the whole InsurancePolicy object and put the values in a map.
when i try it with InsurancePolicy i get exception cannot convert InsurancaCalculation into String,
my Insurance policy object looks like this
class InsurancePolicy {
#OneToOne
private Person person;
#OneToOne
private Vehicle vehicle;
#OneToOne
private InsurancePolicyStatus status;
private LocalDate policyStart = LocalDate.now().plusDays(1);
private LocalDate policyEnd = policyStart.plusYears(1).minusDays(1);
private boolean policy_AC = true;
private boolean policy_OC = true;
private boolean policy_ASS;
private boolean policy_NNW;
private String vehicleUsageType;
InsuranceCalculation calculation
#Embedded
private InsuranceVehicle insuranceVehicle;
#Embedded
private InsuranceCustomer customer;
private String coownerHowMany;
private String abroad;
}
Finally my question how can i improve my method getValueMapFromInsuranceVehicle() to get more fields copied ?
basically how to make this code below to work
public Map<String, Object> getValueMapFromInsuranceVehicle(Long insuranceId) throws InvocationTargetException, IllegalAccessException {
InsurancePolicy insurance = repository.findById(insuranceId).get();
Method[] methods = insurance.getClass().getMethods(); // insurance instead of vehicle
Map<String, Object> map = new HashMap<String, Object>();
for (Method m : methods) {
if (m.getName().startsWith("get")) {
Object value = m.invoke(insurance); // insurance instead of insurancevehicle
map.put(m.getName().substring(3), value);
}
}
// add other fields specific to our needs like currentYear
return map;
}
To get the methods of other objects in InsurancePolicy you could use your same code but add some checks for if the object is InsuranceCustomer, InsuranceVehicle, or InsuranceCalculation by using instanceOf and if it is use the same code just with Method[] methods = insurance.getClass().getMethods(); changed to the objects class. I would recommend separating your code into more methods so you can use recursion.

Java : How to create map using the class attributes?

I am trying to create a map from all the attributes that a class have.My class looks like :
public class MyInventory
{
private int tiers = 80;
private int stearing =135;
private int battery = 46;
}
Now I have collected all the methods that the class has as :
Field[] fields = this.getClass().getDeclaredFields();
Now , I am trying to create a Map out of it where keys are the values of the fields and the values are the name of the fields. Example :
Map<46,battery> ...etc
Is there a way to do it?
The attribute values for the above mentioned class were generated by mapping to properties file and by using spring annotation #ConfigurationProperties. Now I need to create the Map but keys the values of the attributes. I tried to use reflect. However did not find a way to get the value of the fields.
Thanks
You can use Introspector class.
public Map<Object, String> populateMap(final Object o) throws Exception {
Map<Object, String> result = new HashMap<>();
for (PropertyDescriptor pd : Introspector.getBeanInfo(o.getClass()).getPropertyDescriptors()) {
String fieldName = pd.getName();
if("class".equals(fieldName) continue;
Object value = pd.getReadMethod().invoke(o);
result.put(value, fieldName);
}
return result;
}
You can call the above method, passing your class as argument.
MyInventory mi = new MyInventory();
// Sets the properties of mi
mi.setXXX...
// Populates map
populateMap(mi);
Map<Integer, String> map() throws IllegalArgumentException, IllegalAccessException {
Field[] fields = getClass().getDeclaredFields();
Map<Integer,String> map = new HashMap<>();
for (Field field : fields) {
map.put(field.getInt(this), field.getName());
}
return map;
}
Of course it will not map properly if different fields have the same value.
I think, you can have getter method in your class
public class MyInventory
{
private int tiers = 80;
private int stearing =135;
private int battery = 46;
public int getBattery()
{
return battery;
}
//and other getter
}
and then you can populate your map as
map.put(inventory.getBattery(),"battery");
Because, when you have value, which means you know what is the type for which you are populating map.
You can use json parser. For example jackson:
import com.fasterxml.jackson.databind.ObjectMapper;
...
ObjectMapper mapper = new ObjectMapper();
return mapper.readValue(mapper.writeValueAsString(fooOject), HashMap.class);

How can I get Map getters values

I create Details class and that class create Map object. and set getters setters.
setdatavalues class I set values to the setters
Then I try to get that values in getdatavalues class. by calling getters methord.
problem is I cannot get values in that getters. display empty array.
In getdatavalues calss I create mymap object and assign getMyMap() method and display the values
public class Details{
private Map<String, String> myMap = new LinkedHashMap<String, String>();
public Details() {
super();
}
public Map<String, String> getMyMap() {
return myMap;
}
public void setMyMap(Map<String, String> myMap) {
this.myMap = myMap;
}
}
public static void setdatavalues(){
LinkedHashMap<String, String> myMap=new LinkedHashMap<String, String>();
ArrayList<String> fields,values=new ArrayList<String>();
Details details= new Details();
|
|
fields=readNumbers();
values=readStrings();
for(int j=0;j<fields.size();j++)
{
myMap.put(fields.get(j),values.get(j));
}
details.setMyMap(myMap);
}
}
public static void getdatavalues(){
Details details= new Details();
//System.out.println(details.getMyMap().values());
Map<String,String> mymap = details.getMyMap();
System.out.println(mymap.values());
}
output
details that is set values is setdatavalues is thrown away and new empty details is used in getdatavalues. You must pass the Details object that is set data to where data in Details object is printed to print the data set.

prevent protected variable access from child class without using getter and setter in java

Without using getter and setter method how to prevent modification access from child class if super class has protected Hashmap variable?
This Map is mutable (So i should be able to add the values from super class)So can't use UnmodifiableMap(its only applicable immutable collection object)
Class A
{
protected Map<Integer,Integer> m = new HashMap<Integer,Integer>();
A()
{
m.put(10,11)
m.put(11.12)
}
}
Class B extends A
{
B()
{
super.m.put(34,90) —— I don’t want to give access to child class to add
the value and child class and its only should able to get the values.
}
}
Make the map unmodifiable, and populate it in the construction of A.
class A {
protected final Map<Integer,Integer> m;
A() {
Map<Integer, Integer> tempMap = = new HashMap<>();
tempMap.put(10,11);
tempMap.put(11.12);
this.m = java.util.Collections.unmodifiableMap(tempMap);
}
}
If and when B attempts to modify the map, a ´UnsupportedOperationException´ will be thrown.
If you want A to be able to modify the map, then you'll need a different approach in which the map is private, and a protected getter returns an unmodifiable map.
class A {
private final Map<Integer,Integer> m = new HashMap<>();
A() {
m.put(10,11);
m.put(11.12);
// m remains modifiable within the context of A
}
protected Map<Integer, Integer> getMap() {
return java.util.Collections.unmodifiableMap(m);
}
}
EDIT
If you really don't want to use a getter but still have read-only access, you can use this approach.
class A {
private final Map<Integer,Integer> writableMap = new HashMap<>();
protected final Map<Integer,Integer> m = Collections.unmodifiableMap(writableMap);
A() {
writableMap.put(10,11);
writableMap.put(11.12);
}
}
Using this approach, only m is visible outside A, and is read-only. Within A, you can update writableMap and these changes will be visible in m
Here is a variant of what Steve Chaloner presented in his answer:
public class A {
private final Map<Integer, Integer> map = new HashMap<>();
protected final Map<Integer,Integer> m = Collections.unmodifiableMap(map);
public A() {
map.put(10, 11);
map.put(11, 12);
}
}
The private map is modifiable in the A class and changes will be reflected in the protected m whenever changes are made in map.
It is being used this way in Concurrency In Practice for example.
This should be the best solution Composition:
Implement a new Map and keep an internal private modifiable map like this:
class A {
private Map<Integer,Integer> m = new HashMap<>();
protected Map<Integer, Integer> map = new Map<>() {
//implement interface
public Integer put(Integer key, Integer value) {
throw new UnsupportedOperationException();
}
public Integer get(Object key) {
return m.get(key);
}
public void clear() {
throw new UnsupportedOperationException();
}
public boolean containsKey(Object key) {
return m.containsKey(key);
}
public boolean containsValue(Object value) {
return m.containsValue(value);
}
//
// ... And so on
//
// ... with all other methods
}
A() {
m.put(10,11)
m.put(11.12)
}
}
class B extends A {
B() {
super.map.put(34,90) // thorws exception
super.m.put(34,90) // inaccesible
}
}
All modifications are allowed in A via m but subclasses may only acces them by map that was succesfully blocked modifications.

Populating hashmap from a hashset from an other class

I have a hashset in a class called myClass that contains 6 strings.
I want to be able to create a hashmap and use these 6 strings as keys in another class called Maps, and they values beside.
how can i call the hashmap from the map class and use the 6 Strings from the hashset in myClass.
public class MyFavouriteClasses {
Set<String> classes;
public MyFavouriteClasses() { }
public Set populate() {
Set<String> classes = new HashSet<String>();
classes = new HashSet<String>();
classes.add("ArrayList");
classes.add("Hashset");
classes.add("Random");
classes.add("AbstractList");
return classes;
}
}
public class MyFavoriteMapClass {
Map<String, String> map;
public MyFavoriteMapClass() { }
public void populate() {
MyFavouriteClasses class = new MyFavouriteClasses();
map = new HashMap<String, String>();
Set<String> classes = class.populate();
for(String str:classes) {
map.put(String, (Class)str.getPackage());
}
}
}

Categories

Resources