8

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);
}
9
  • I believe something like this would work in Java8 Map<Integer, QueryStrings> queryMap = queryStrings.stream().collect(toMap(element.getId(), element)); Commented Jun 29, 2017 at 4:54
  • Why call parseInt()? id is already of type Integer, just use the ID directly. Commented Jun 29, 2017 at 4:54
  • @ScaryWombat id is Interger right ?why we need to parse Commented Jun 29, 2017 at 4:56
  • Minus the extra call as noted in the current answer, looping is as "efficient" as any other method. Define "better way". Commented Jun 29, 2017 at 4:58
  • 2
    This is not worth worrying about. You can populate millions of items into a HashMap per second, as long as the hashcodes aren't degenerate. Commented Jun 29, 2017 at 5:57

1 Answer 1

7

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()));
Sign up to request clarification or add additional context in comments.

2 Comments

His class does show it as an Integer though
did not catch that - definitely a better way to do is not to go from Integer -> String -> Integer :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.