I am using OpenCsv to get a table of values with dates as column headers, which looks something like this:
| Country | 1/01/22 | 1/02/22 | 1/03/22 | ... |
|---|---|---|---|---|
| Ireland | 0 | 5 | 150 | ... |
| Japan | 7 | 189 | 3323 | ... |
I am new to OpenCsv and functional programming in general, and after reading the OpenCsv user guide and trying for a few days, I managed:
@CsvBindByName(column="Country/Region",required=true)
private String country;
@CsvBindAndJoinByName(column="[0-9]{1,2}/[0-9]{1,2}/[0-9]{1,4}", elementType = String.class, mapType = ArrayListValuedHashMap.class)
private MultiValuedMap<String,String> cases;
private TreeMap<LocalDate, List<String>> sortedCases = new TreeMap<>();
public String getCountry() {return country;}
public MultiValuedMap<String, String> getCases() {return cases;}
public void addToSortedCases(MultiValuedMap<String,String> map) {
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("M/d/yy");
for(String key:map.keys()){
sortedCases.put(LocalDate.parse(key,dateFormat),map.get(key).stream().toList());
}
}
//attempt on converting addToSortedCases to Functional Interface.
public BiConsumer<MultiValuedMap<String,String>, List<String>> addToSorted = (map, keys) ->
keys.forEach(key ->
sortedCases.put(
LocalDate.parse(key,DateTimeFormatter
.ofPattern("M/d/yy")),
Integer.valueOf(map.get(key)
.toString()
.replaceAll("[\\[\\]]",""))
));
@Override
public String toString() {
return "Confirmed{" +
"country='" + country + '\'' +
", cases=" + sortedCases.toString() +
'}';
}
the addToSorted functional interface doesn't work when I use it in place of the addToSortedCases method in main, with the error being "Method call expected". I think I wrote the functional interface correctly but I'm not sure.
...
public static List<Recovered> recoveredCases;
public static void main(String[] args) {
...
recoveredCases = (List<Recovered>) readFile.apply(Recovered.path,Deaths.class);
recoveredCases.forEach(recovered -> recovered.addToSortedCases(recovered.getCases()));//works
recoveredCases.forEach(recovered -> recovered.addToSorted(recovered.getCases(),recovered.getCases().keys()));//doesn't work
}
public static BiFunction<String,Class<?>, List<?>> readFile = (path, classType) -> {
try {
return new CsvToBeanBuilder(new FileReader(path))
.withType(classType)
.build()
.parse();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
};
I'd appreciate it very much if I could get a solution to this problem, or even better, have OpenCsv sort the MultiValuedMap or use a TreeMap directly.