Hi is right pass HashMap to functions in repository
void sendComment(HashMap<String, String> data){
FirebaseDatabase.getInstance(). getRefrence().setValue(data);
}
And in viewmodel i create HashMap var and add key,value to it like
HashMap<String, String> data=new HashMap<>();
data.add("commentText","any text");
data.add("senderId","any text");
data.add("postId","any text");
repo.sendComment(data);
Is that true or should i add arguments senderId,postId,commentText
In function in repository
Like
void sendComment(String postId,String senderId){
//Add to database code
}
first of all you can use SparseArray instead of HashMap . because SparseArray is intended to be more memory-efficient than a HashMap, because it avoids auto-boxing keys and its data structure doesn't rely on an extra entry object for each mapping
depends on your task .
SparseArray<Int>().set(key , value)
you can use the repository for change any object(data) to save in DB or send to the server and change any object(data) to pass to ui and viewModel .
Related
I have a ConcurrentHashMap that looks like this:
private Map<String,Map<String,Set<PublicKey>>> instancePairs = new ConcurrentHashMap<>();
And a method that is supposed to fill this hashmap up.
But i can't figure out how to put the values in the map
Currently i have:
instancePairs.putIfAbsent(inMemoryInstance.getUsername(), inMemoryInstance.getId() , publicKeySet);
Intellij Idea is giving me this error:
As mentioned by "DDovzhenko", you'd need to do something along the following lines.
//Get the map containing the ID as keys, if it doesn't exist, then create one.
Map mapValuesForName = instancePairs.getOrDefault(inMemoryInstance.getUsername(), new ConcurrentHashMap<String,Set<PublicKey>>());
//Put the publicKeySet based on the Id.
mapValuesForName.putIfAbsent(inMemoryInstance.getId(), publicKeySet);
//Store the potentially changed/new value back in original map.
instancePairs.put(mapValuesForName);
I welcome methods in the API to easily create default initialisations.
For example in HashMaps. But why have they not been provided with Supplier Lambda methods? - Or am I missing an important step, or did I not learn the latest java Api versions?
Standard (Java8) version:
Map<String,List<Integer>> datas = new HashMap<>();
List<Integer> integersList = datas.getOrDefault( "somekey", new ArrayList<>() );
which would instantiate a new ArrayList anytime the code is executed - no matter if the new list is needed or not.
Desired Lambda supplier version:
Map<String,List<Integer>> datas = new HashMap<>();
List<Integer> integersList = datas.getOrDefault( "somekey", ()->new ArrayList() );
Would instantiate (or execute some instantiation code) only in case demanded key is not within the map.
The code of the getOrDefault()-Method could look something like this:
public V getOrDefault( K key, Supplier<V> supplier ) {
if ( !super.containsKey( key ) && supplier != null ) {
super.put( key, supplier.get() );
}
return super.get( key );
}
Why did they(?) not build it that way initially or added such functionality later on?
I guess there is even more examples where Lambda would solve an unnecessary code execution - not just Maps as shown with this example.
By the way: sorry for re-asking a question but I would not know how to exactly look for my question with different terms...
Be welcome to post helpful links.
Thanks for your shared knowledge :-)
What you are looking for exists since Java 8. Take a look at the javadoc of the HashMap and specifically the method Hashmap.computeIfAbsent. This method allows for adding new entries to the HashMap if none can be found using the key provided.
Examaple:
Map<Integer, String> map = new HashMap();
String created = map.computeIfAbsent(1, k -> "Test");
System.out.println(created);
The code above will trigger the HashMap to call the provided Function to add a new entry since it cannot find an existing one. It both returns the new entry and call the Hashmap.put method to add it.
I need to do Volley POST method with this kind of body for onResponse method:
{"table":{"ma":1,"mb":2},"token":"access"}.
So basically I need HashMap called "params" that takes multiple key-value pairs as values for "table" key, and single value for"token" key, that goes inside Volley request.
I tried to do this,but it requires List for second argument for "token" value
Map<String, List<String>> params = new HashMap<>();
// Hash map for "ma"
HashMap<String, String> maParams = new HashMap<>();
maParams.put("ma", "1");
Hash map for "mb"
HashMap<String, String> mbParams= new HashMap<>();
mbParams.put("mb", "2");
// Table values
List<String> values = new ArrayList<>();
values.add(String.valueOf(maParams));
values.add(String.valueOf(mbParams));
params.put("table", beacons);
params.put("token", "access");
Any ideas how I can do that?
Thanks in advance.
What you require in your body actually looks like JSON. As I don't actually understand what you are trying to achieve with your code I would instead suggest that you take a look to famous JSON APIs such as Jackson or give a try to JSONObject . You will easily find ways to build an object just like you asked {"table":{"ma":1,"mb":2},"token":"access"}.
If overkill for you then just write pure Java to achieve what you want: build a map of tokens (instead of 2 Maps + 1 List) and write a formatting method to put it like you want in your params. Note: as {"ma":1,"mb":2} is not double-quoted in your example then what params must look like is more certainly a simple String (and not any kind of Map!). Actually this is JSON..
EDIT: you are strongly advised to have a look to these posts:
How to send a POST request with JSON body using Volley?
Android Volley POST Json to Server
Send POST request with JSON data using Volley
How to send a POST request using volley with string body?
Which all look like possible duplicates..
I have to store some machine details in redis. As there are many different machines i am planning to use the below structure
server1 => {name => s1, cpu=>80}
server2 => {name => s2, cpu=>40}
I need to store more than one value against the key CPU. Also i need to maintain only the last 10 values in the list of values against cpu
1) How can i store a list against the key inside the hash?
2) I read about ltrim. But it accepts a key. How can i do a ltrim for key cpu inside server1?
I am using jedis.
Redis' data structures cannot be nested inside other data structures, so storing a List inside a Hash is not possible. Instead, use different keys for your servers' CPU values (e.g. server1:cpu).
It's possible to do this with Redisson framework. It allows to store a reference to Redis object in another Redis object though special reference objects which handled by Redisson.
So your task could be solved using List inside Map:
RMap<String, RList<Option>> settings = redisson.getMap("settings");
RList<Option> options1 = redisson.getList("settings_server1_option");
options1.add(new Option("name", "s1"));
options1.add(new Option("cpu", "80"));
settings.put("server1", options1);
RList<Option> options2 = redisson.getList("settings_server2_option");
options2.add(new Option("name", "s2"));
options2.add(new Option("cpu", "40"));
settings.put("server2", options2);
// read it
RList<Option> options2Value = settings.get("server2");
Or using Map inside Map:
RMap<String, RMap<String, String>> settings = redisson.getMap("settings");
RMap<String, String> options1 = redisson.getMap("settings_server1_option");
options1.put("name", "s1");
options1.put("cpu", "80");
settings.put("server1", options1);
RMap<String, String> options2 = redisson.getMap("settings_server2_option");
options2.put("name", "s2");
options2.put("cpu", "40");
settings.put("server2", options1);
// read it
RMap<String, String> options2Value = settings.get("server2");
Diclamer: I'm a developer of Redisson
You can encode/stringify push the data, while pulling data you can decode/parse the data.
Encode -> Decode
Stringify -> Parse
I got the following variables
List<Pruefvorschrift> listP = new ArrayList<Pruefvorschrift>();
ObservableMap<TestDevice,List<Pruefvorschrift>> testDev = FXCollections.emptyObservableMap();
in one function i want to fill the testDev by using lambda expression
//first call REST service and get data
List<TestDevice> test_dev = call.getTestDevice("");
//now do a foreach to add each entry (as key) to the testDev ObservableMap with a empty List (as value)
test_dev.stream().forEach(td ->{
TestDevice t = td;
testDev.put(t, listP);
});
but all i get is a error
java.lang.UnsupportedOperationException at
java.util.AbstractMap.put(AbstractMap.java:209)
which obviously is this row
testDev.put(t, listP);
maybe i misunderstood the new stream api but i only want to fill the observable map with all the result of the call (key) and an empty List (value which will be modified later).
Any help? Thx
Whatever Map type is returned by FXCollections#emptyObservableMap
FXCollections.emptyObservableMap();
does not support the put method. You can't add anything to it. As the javadoc states
Creates and[sic] empty unmodifiable observable list.
This has nothing to do with lambda expressions or the Stream api.
just to complete here (Sotirios Delimanolis was absolute right and me so wrong :). My problem was solved by doing a correct job with the map itself
//create empty map
Map<TestDevice,List<Pruefvorschrift>> map = new HashMap<TestDevice,List<Pruefvorschrift>>();
//use this map to create the ObservableMap
ObservableMap<TestDevice,List<Pruefvorschrift>> testDev = FXCollections.observableMap(map);
And all works...Thx Sotirios