-3

I have a list of Dates coming as a request:

requestedDateRange = ["2020-09-10","2020-05-06","2020-04-11"]

I want to convert this list into a map with keys as the map and emptyList in the values which will be populated later.

2020-09-10 -> []

2020-05-06 -> []

2020-04-11 -> []

What I did is as follows :

Map<LocalDate, HashSet<String>> myMap = new HashMap<>();

for (LocalDate date : requestedDateRange){
       myMap.put(date, new HashSet<>());
}

Used hashSet to have only unique values

How can I do it in a better way or using Java8 features?

2 Answers2

2

This should do the trick:

Map<LocalDate, List<String>> myMap = 
    requestedDateRange.stream()
                      .collect(toMap(identity(), d -> new ArrayList<>()));

or this:

Map<LocalDate, Set<String>> myMap = 
    requestedDateRange.stream()
                      .collect(toMap(identity(), d -> new HashSet<>()));
ETO
  • 6,970
  • 1
  • 20
  • 37
0

I hope this is what you need:

    public static void main(String[] args) {
    //Create ArrayList and TreeMap
    ArrayList<LocalDate> requestedDateRange = new ArrayList<>();
    TreeMap<LocalDate, HashSet<String>> treeMap = new TreeMap<>();

    //Add necessary data to ArrayList
    requestedDateRange.add(LocalDate.parse("2020-09-10"));
    requestedDateRange.add(LocalDate.parse("2020-05-06"));
    requestedDateRange.add(LocalDate.parse("2020-04-11"));

    //For each data in ArrayList add this data as key and add and empty String Array
    requestedDateRange.forEach(s -> {
        treeMap.put(s,new HashSet<>());
    });

    //Print TreeMap
    System.out.println(treeMap.toString());
}
Miko
  • 17
  • 5