Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I was implementing a Java program containing hash maps, I wanted to use two different hash-maps and a boolean function. So for every key, depending on the boolean outcome, it would select one of the hash-maps. What would be some disadvantages/advantage of this?
There are two ways to do this (as far as I can think of at the moment):
Method 1: (from #WJS in the comments)
Have a HashMap with a boolean key and the corresponding HashMap as the value. Like so:
HashMap<Boolean, Map<Key, Value>> outer = new HashMap<>();
Method 2:
Since there can only be two HashMaps corresponding to your boolean true or false value, I don't think you need to have another HashMap and can simply use a boolean variable.
For Example:
// or similar depending on your implementation and needs; can be
// extended for choosing get(), set(), etc.
boolean flag;
HashMap<Key, Value> trueMap = new HashMap<>();
HashMap<Key, Value> falseMap = new HashMap<>();
HashMap<Key, Value> map = flag ? trueMap : falseMap;
There is no downside to having HashMaps chosen like this and is actually fairly common.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 months ago.
Improve this question
Why is the following code a bad practice and what is the solution for it?
TreeSet<Map.Entry<Integer, Map<String, String>>> sortedtable = new TreeSet<>(new ComparatorByDueDate());
public void sortTable(Map<Integer, Map<String, String>> table){
sortedtable.addAll(table.entrySet());
}
Update: As per Sonar, it is a bad practice. I am asking the question here as the sonar explanation seems confusing.
Java Map.Entry objects are not intended for long term storage. From the docs (emphasis mine),
A map entry (key-value pair). The Map.entrySet method returns a collection-view of the map, whose elements are of this class. The only way to obtain a reference to a map entry is from the iterator of this collection-view. These Map.Entry objects are valid only for the duration of the iteration; more formally, the behavior of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator, except through the setValue operation on the map entry.
If anyone, for any reason, adds, removes, or modifies any part of the map after the fact, then your TreeSet entries now have undefined behavior. They might still be good, they might get nulled out, they might exhibit some random behavior.
If you want to store a pair of elements, then write a class that has two instance variables. If you're on a new enough Java version, then records are great for this sort of thing.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have the following map:
Map<String, Map<String, Map<String, Map<String, List<Person>>>>>
I want to get a List<Person> that is the value in the fourth map.
How can I do it in Java 8, i.e., how can I retrieve the value of the innermost map?
You have several nested maps, so each call to get will return the respective value (which is a deeper map) and will eventually get you to the list. In order to call methods in empty maps, use Map.getOrDefault() instead of get().
import static java.util.Collections.emptyList;
import static java.util.Collections.emptyMap;
List myList = myMap
.getOrDefault("key1", emptyMap())
.getOrDefault("key2", emptyMap())
.getOrDefault("key3", emptyMap())
.getOrDefault("key4", emptyList());
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I have the below code for tree map where I store duplicate key and it seems overwrite the existing one.
TreeMap<String, Integer> tm=new TreeMap<>();
tm.put("vivek", 1);
tm.put("vivek", 2);
System.out.println(tm);
It prints {vivek=2} So it means map allow to overwrite on key basis?
All maps share the same basic properties, one of which is that all keys must be unique. Hence why keySet() returns a Set.
To do what you are looking for you need a Multimap - which is essentially a Map to a List.
Map<Integer, List<String>> multiMap;
To add an object get the list for that key, if it is null add a list then add your value to the list, otherwise just add your value to the existing list.
There are some multimap implementation available in various 3rd party libraries or it's easy enough to implement your own.
TreeMap#public V put(K key, V value) API says
Associates the specified value with the specified key in this map.
If the map previously contained a mapping for the key, the old value is replaced.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a HashSet which contains the keys of a HashMap, and update the contents of the HashMap, adding a new key in the process. After I've done this, I then want to use the HashSet of keys again, since I know that they kept up to date with the keys of the HashMap. I just want to make sure that this is all done by the same thread, and that there is no concurrency going on here that I might be unaware of, such that I tell the HashMap to add the new entry, and before it has updated I have used the HashSet information while it is out of date.
In code:
HashMap<String, Integer> myHashMap = new HashMap<String, Integer>();
HashSet<String> myHashSet = myHashMap.keySet();
... processing ...
myHashMap.put(new_key, value);
... use the **original** HashSet of keys, myHashSet ...
Could the above situation occur, given that this is the only thread created by the programmer, such that myHashMap and myHashSet would be out of sync? I'm not talking about the programmer creating more than one thread - the main program runs in a single thread (see above).
No they won't because the key set is a view onto the actual keys in the HashMap.
From the Javadocs:
The set is backed by the map, so changes to the map are reflected in
the set, and vice-versa.
And you can see the same in OpenJDK's implementation of HashMap.
So for a single-threaded program these should always be in sync.
The Java collections classes don't do things with threads internally because it would make using them too difficult and error prone. They leave the threading model to the calling code and just provide guarantees (or otherwise) about which operations are thread-safe.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Just wondering if there is a better approach to building to the web app that I'm creating? I'm not going to show a lot of code, I'm more interested in following best practices:
Index.html contains a static form
User fills out the form and the POST request is handled by a Java Servlet
The servlet contains 3 methods:
doPost(HttpRequest,
HttpResponse)
doGet(HttpRequest, HttpResponse)
processRequest(Map map)
doPost() constructs a hashmap and assigns all of the variables from the form to it in key:value format. Then it calls the method processRequest(Map map)
processRequest(Map map) has one function: to create a new instance of class formParser with the map variable: i.e. formParser parser = new formParser(map);
The class formParser has a constructor and a method:
the constructor initializes a new HashMap which clones the original and a new LinkedList which is to store the values and calls the method with the map parameter
Map<String, String> paramMap = new HashMap<String, String>(map);
List<String> paramList = getParams(paramMap);
The method public LinkedList<String> getParams(Map paramMap) then checks all of the key:value pairs in the map and only takes those that have no null values
I then use the valid key:value pairs to write certain XML snippets to a pre-existing XML skeleton, which is sent to an external REST-API. I have yet to write this code.
EDIT: I should add that I'm new to Java Web programming, and this is why I'm only trying to validate the efficacy of my approach to the program, rather than the code itself. That will come later.
I think that step 6 can be improved a little by not creating the LinkedList. If I understand correctly the LinkedList is used to remove NULL values. This can be achieved by iterating over the keys of the map, retrieving their value and removing any keys from the map that have NULL values.
Map map = new HashMap<String, String>();
map.put("name1","somevalue");
map.put("name2",null);
for(String s : map.keySet()){
String value = map.get(s);
if ( s == null){
map.remove(s);
}
}
I don't know what you exactly mean by "efficiency", but if you are talking about performance, I don't see anything crazy being done in the steps you describe, and IMO that's enough.
Go with the simplest, most usual design and you can improve performance if there is a problem. In my experience, 99.999% of performance problems in web apps come from doing crazy stuff (i.e. unusual, complex approaches).
Since you are new to web programming you should not consider performance problems.
Just focus on working code.