I have a list here:
List<QueryStrings> queryStrings
and QueryStrings is just a simple class
public class QueryStrings {
private Integer id;
private String rel;
private String impl;
}
I need to put the List into a HashMap where the id will be the key, I am doing it like this right now, looping the List one item at a time:
HashMap<Integer, QueryStrings> queryMap = new HashMap<>();
for (QueryStrings element : queryStrings) {
Integer thisId = Integer.parseInt(element.getId());
queryMap.put(thisId, element);
}
Is there a better way to this? I do not want to loop each items, is that possible?
Edit:
Sorry I should not parse the integer, so the code should look like:
HashMap<Integer, QueryStrings> queryMap = new HashMap<>();
for (QueryStrings element : queryStrings) {
queryMap.put(element.getId(), element);
}
Duplicates: HashSet doesn't allow duplicate values. HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.
The ArrayList has O(n) performance for every search, so for n searches its performance is O(n^2). The HashMap has O(1) performance for every search (on average), so for n searches its performance will be O(n). While the HashMap will be slower at first and take more memory, it will be faster for large values of n.
However, none of the existing Java core Map implementations allow a Map to handle multiple values for a single key. As we can see, if we try to insert two values for the same key, the second value will be stored, while the first one will be dropped.
Don't parse the int's if it's already an int!
HashMap<Integer, QueryStrings> queryMap = new HashMap<>();
for (QueryStrings element : queryStrings) {
queryMap.put(element.getId(), element);
}
That said, if it's Java 8 you can have more concise syntax, although the performance differences are minimal.
list.stream().collect(Collectors.toMap(QueryStrings::getId, Function.identity()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With