使用 Java8 将列表转换为地图,并将空列表作为值
Convert list to map using Java8, with empty list as values
我有一个日期列表作为请求:
requestedDateRange = ["2020-09-10","2020-05-06","2020-04-11"]
我想将这个列表转换成一个映射,其中键作为映射,值中的空列表将在稍后填充。
2020-09-10 -> []
2020-05-06 -> []
2020-04-11 -> []
我做的是这样的:
Map<LocalDate, HashSet<String>> myMap = new HashMap<>();
for (LocalDate date : requestedDateRange){
myMap.put(date, new HashSet<>());
}
使用 hashSet 仅具有唯一值
我怎样才能以更好的方式或使用 Java8 功能来做到这一点?
这应该可以解决问题:
Map<LocalDate, List<String>> myMap =
requestedDateRange.stream()
.collect(toMap(identity(), d -> new ArrayList<>()));
或者这个:
Map<LocalDate, Set<String>> myMap =
requestedDateRange.stream()
.collect(toMap(identity(), d -> new HashSet<>()));
我希望这是你需要的:
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());
}
我有一个日期列表作为请求:
requestedDateRange = ["2020-09-10","2020-05-06","2020-04-11"]
我想将这个列表转换成一个映射,其中键作为映射,值中的空列表将在稍后填充。
2020-09-10 -> []
2020-05-06 -> []
2020-04-11 -> []
我做的是这样的:
Map<LocalDate, HashSet<String>> myMap = new HashMap<>();
for (LocalDate date : requestedDateRange){
myMap.put(date, new HashSet<>());
}
使用 hashSet 仅具有唯一值
我怎样才能以更好的方式或使用 Java8 功能来做到这一点?
这应该可以解决问题:
Map<LocalDate, List<String>> myMap =
requestedDateRange.stream()
.collect(toMap(identity(), d -> new ArrayList<>()));
或者这个:
Map<LocalDate, Set<String>> myMap =
requestedDateRange.stream()
.collect(toMap(identity(), d -> new HashSet<>()));
我希望这是你需要的:
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());
}