Showing posts with label HashMap. Show all posts
Showing posts with label HashMap. Show all posts

Friday, December 1, 2017

How to convert List into a hashMap?

Question:

I'm capturing parameters from a request url using com.apache.http.NameValuePairwhich basically store those params in List<NameValuePair>. To do certain checks and verifications on those params, I need to convert that list into a HashMap<String, String>. Is there a way to do this conversion?

Answer:

You can use it for Java 8
public static <K, V, T extends V> Map<K, V> toMapBy(List<T> list,
        Function<? super T, ? extends K> mapper) {
    return list.stream().collect(Collectors.toMap(mapper, Function.identity()));
}
And here's how you would use it on a List:
Map<Long, Product> productsById = toMapBy(products, Product::getId);
Follow the link:
  1. Converting ArrayList to HashMap
  2. Generic static method constrains types too much
  3. Java: How to convert List to Map

How to get the first key of a hashmap?

Question:

I have the following HashMap<String, Double> map = new HashMap<String, Double>();
How can i get the first key without iterating over it like this:
Iterator it = map.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pair = (Map.Entry)it.next();
    System.out.println(pair.getKey() + " = " + pair.getValue());
    it.remove(); 
}
Thanks

Answer:

To get the value of the "first" key, you can use it
map.get(map.keySet().toArray()[0]);

In Java8,

You can use stream. For TreeMap/LinkedHashMap, where ordering is significant, you can write
map.entrySet().stream().findFirst();
For HashMap, there is no order, so findAny() might return a different result on different calls
map.entrySet().stream().findAny();
Original Link:  How to get the first key of a hashmap?