Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Putting items from List into HashMap efficiently [duplicate]

Tags:

java

hashmap

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);
}
like image 908
Steven Yong Avatar asked Jun 29 '17 04:06

Steven Yong


People also ask

Does HashMap accept duplicate values Java?

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.

Are Hashmaps faster than ArrayList?

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.

Does Java map allow duplicates?

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.


1 Answers

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()));
like image 141
Ryan Leach Avatar answered Sep 22 '22 08:09

Ryan Leach