-1

I am trying to convert a properties object into a HashMap<String, String>. I am able to convert it to a Map, but not able to do it diectly to a HashMap.

So far, I have done this:

dbProperties.entrySet().stream().collect(Collectors.toMap(k -> k.getKey().toString(), v -> v.getValue().toString()));

This gives me a Map<Object, Object>. Is there way to get it to a HashMap<String, String> without casting or anything?

Yassin Hajaj
  • 21,337
  • 9
  • 51
  • 89
hell_storm2004
  • 1,401
  • 2
  • 33
  • 66

1 Answers1

2

You can do it by providing a BinaryOperator and Supplier.

import java.util.HashMap;
import java.util.Properties;
import java.util.stream.Collectors;

public class Main {
    public static void main(String args[]) {
        Properties dbProperties = new Properties();
        dbProperties.put("One", "1");
        dbProperties.put("Two", "2");

        HashMap<String, String> map = 
                dbProperties.entrySet()
                            .stream()
                            .collect(Collectors
                                        .toMap(k -> k.getKey().toString(), 
                                                v -> v.getValue().toString(), 
                                                (v1, v2) -> v1, 
                                                HashMap::new
                                        )
                            );
        System.out.println(map);
    }
}

Output:

{One=1, Two=2}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110