How can I get Map getters values - java

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.

Related

different setter method for HashMap<>

I have a Class like this:
public class MyClass
{
private int id;
private Map<String, String> myMap;
public Map<String, String> getMyMap()
{
return myMap;
}
public void setMyMap(Map<String, String> myMap)
{
this.myMap = myMap;
}
}
I added new setter method(overloading) because i didn't want to do set HashMap directly, and that's what you see now :
public class MyClass
{
private int id;
private Map<String, String> myMap;
public Map<String, String> getMyMap()
{
return myMap;
}
public void setMyMap(Map<String, String> myMap)
{
this.myMap = myMap;
}
public void setMyMap(String key , String value)
{
setMyMap(new HashMap<>(){{put(key, value);}});
}
}
But because i used new HashMap<>(){{put(key, value);}} keyword every time i use this method , it create new Map and last items deleted .
So i have 2 question:
1-correct solution for set items by 2nd setter method
2-how i could use this setter method for multiple put's for this situations:
MyClass.setMyMap(new HashMap<>()
{{
put("title", title);
put("id", id);
}});
Thank you guys for your time .
It depends on what your class does. But in general, I would not expose a setter for a map field.
It makes sense to add a constructor with a map argument, then do something like this:
public class MyClass
{
private final int id;
private final Map<String, String> myMap;
public MyClass(int id, Map<String, String> myMap) {
this.id = id;
this.myMap = myMap;
}
public Map<String, String> getMyMap()
{
return myMap;
}
public void addPairs(Map<String, String> pairs)
{
myMap.putAll(pairs);
}
public void addPair(String key, String value)
{
myMap.put(key, value);
}
}
Of course, you can expose an additional constructor:
public MyClass(int id) {
this.id = id;
this.myMap = new HashMap<>();
}
Try some thing like this:
public void setMyMap(String key , String value) {
if(myMap == null)
myMap = new HashMap<String, String>();
myMap.put(key, value);
}
You've already declared class field myMap and you want to use it in setMyMap method.
Do null check. If the field is null then create a new map. Then use put method to store data in the map.

Restrict calling static setter method only once

I have the below code :
public final class SomeStaticClass {
private static Map<String, Map<String,String>> tMap;
private SomeStaticClass(){
//Private Constructor to avoid instance creation
}
//getter method here to retrieve the map.
public static void setMap(Map<String, Map<String,String>> map){
tMap = map;
}
}
I want to restrict the setMap method to be called only once,so that the tMap cannot be modified later.
The tMap will be set only once during application startup and will be access by multiple objects later.
public static void setMap(Map<String, Map<String,String>> map){
if (null == tMap) // This will make sure tMap initialized only once
tMap = map;
}

Create a Map of all the parameter names and values of a method

I am working on REST API service and each time when exception is occured I need to show in logs params , method and class name where this exception happened. So i have singleton class with method
public void log(final String className,String methodName,final Map<String,String> params,final String cause) {
final StringBuilder result=new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
result.append(entry.getKey()+" "+entry.getValue()+" ");
}
log.info("\n\t\t\tClass: "+className+"\n\t\t\t Method: "+methodName+"\n\t\t\t Params: "+result.toString()+" \n\t\t\t "+"Reason: "+cause);
}
Example of use
public String checkSession(String sid) {
final Map<String, String> params = new HashMap<String, String>();
params.put("sid", sid);
if (sid.isEmpty()) {
logger.log(this.getClass().getSimpleName(), "checkSession", params, " not valid session");
return Enums.Error.WRONG_SESSION.toString();
}
}
However in each method I need to initialize this map with all params. How can I write method that will return Map for all methods?
For example I have two methods
public String createPass(String name,String surname) {
final Map<String, String> params = new HashMap<String, String>();
params.put("name", name);
params.put("surname", surname);
}
public String checkSession(String sid) {
final Map<String, String> params = new HashMap<String, String>();
params.put("sid", sid);
}
And method that I need is something like
public HashMap<String,String> method(String args...){
final Map<String, String> params = new HashMap<String, String>
for(...)
map.put("parameter","parameterName");
}
I think the best you can do here is something like this:
public Map<String,String> paramsToMap(String... params){
final Map<String, String> map = new HashMap<>();
for(int i=0; i<params.length-1; i=i+2) {
map.put(params[i], params[i+1]);
}
return map;
}
And you call it this way:
public String createPass(String name, String surname) {
final Map<String, String> params = paramsToMap("name", name, "surname", surname);
}
public String checkSession(String sid) {
final Map<String, String> params = paramsToMap("sid", sid);
}
I wish we could use reflection, however the parameter names are removed at compile time and you are left with arg0, arg1, etc ... So it is not possible to achieve what you want using reflection. You have to input the parameter names yourself.
Also as a side note, I think you would be better off using a Map<String, Object> and let the log method sort out how to print it out to the logs. Probably using String.valueOf()

How to create a hashmap in java class

This is my code. My intention is create a hashmap with 4 values, then export this class as a jar, add it to another project, and use the hashmap values there.
I'm getting error in all the "hmap.put". I'm unable to understand what I'm doing wrong. Please help.
import java.util.HashMap;
public class MyFirstClass {
private HashMap<Integer, String> hmap = new HashMap<Integer, String>();
hmap.put(2, "Jane");
hmap.put(4, "John");
hmap.put(3, "Klay");
hmap.put(1, "Deena");
public HashMap<Integer, String> gethmap()
{
return this.hmap;
}
public void sethmap(HashMap hmap)
{
this.hmap = hmap;
}
}
import java.util.HashMap;
public class MyFirstClass {
private HashMap<Integer, String> hmap = new HashMap<Integer, String>() {
{
hmap.put(4, "John");
hmap.put(3, "Klay");
hmap.put(1, "Deena");
}
};
public HashMap<Integer, String> gethmap() {
return this.hmap;
}
public void sethmap(HashMap<Integer, String> hmap) {
this.hmap = hmap;
}
}
Above code will help you to get the result which you desire. You should also note that you can not use instance variable directly inside class. you have to use that inside method only.
Java doesn't allow executing any statements outside of the scope of any method, field initialization or static block - that's why you get an error.
I suppose, your intent is to do some initialization with that four lines. And Java has support for such kind of initialization - it is the class constructor. So the proper code would look like the following:
import java.util.HashMap;
public class MyFirstClass {
private HashMap<Integer, String> hmap = new HashMap<Integer, String>();
// this is a constructor
public MyFirstClass() {
hmap.put(2, "Jane");
hmap.put(4, "John");
hmap.put(3, "Klay");
hmap.put(1, "Deena");
}
// here goes your other code
}
This way every object of MyFirstClass you create using new MyFirstClass() will contain the data you put in the constructor.
You can read more about the constructors in Java in the official documentation: https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
There are multiple ways to do this. Easiest one is to just add brackets to your put statements:
import java.util.HashMap;
public class MyFirstClass {
private HashMap<Integer, String> hmap = new HashMap<Integer, String>();
{
hmap.put(2, "Jane");
hmap.put(4, "John");
hmap.put(3, "Klay");
hmap.put(1, "Deena");
}
public HashMap<Integer, String> gethmap() {
return this.hmap;
}
public void sethmap(HashMap hmap) {
this.hmap = hmap;
}
}
You should add a constructor to your class:
public MyFirstClass() {
this.hmap = new HashMap<Integer,String>();
// you can do .put here if you wish
}
And change the hmap field to:
private HashMap<Integer, String> hmap;
You're using a method outside of a method. You cannot call Hashmap.put within the class but outside the method - as was mentioned you want to do that in the constructor of the class
public class MyFirstClass {
public MyFirstClass() { //put it here }
}
You can put it in a static block, just as:
private static final Map<Integer, String> NAME_MAP = new HashMap<Integer, String>() {
private static final long serialVersionUID = 1L;
{
NAME_MAP.put(2, "Jane");
NAME_MAP.put(4, "John");
NAME_MAP.put(3, "Klay");
NAME_MAP.put(1, "Deena");
}
};

How to set value of HashMap in Model class

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

Categories

Resources