I have a stream that outputs a set:
1=[15.01.2021, 30.09.2012]
2=[12.05.2021, 02.01.2021]
3=[14.02.2021]
4=[11.05.2022]
private static void groupDateById (Collection <Logs> firstFileLog, Collection <Logs> second) {
Stream.of (firstFileLog, second)
.flatMap (Collection::stream)
.collect(Collectors.groupingBy(Logs::getId, Collectors.mapping(Logs::getTime,Collectors.toList())))
.entrySet().forEach(System.out::println);
}
I also have a method that checks the difference between dates. Between the first and the second.
// Displays the difference. In this case, one month.
GFG.findDifference("2020-09-12", "2020-10-12");
Is it possible to add this method of calculating the date difference to the stream? To immediately calculate for all dates.
I need to get this output
1=[15.01.2021, 30.09.2012], difference(second date - first) 99 month
2=[12.05.2021, 02.01.2021], difference(second date - first)..
3=[14.02.2021] - ignore
4=[11.05.2022] - ignore
It seems like you have an xyproblem. It is not clear, at least to me, what you are trying to achieve. You may want to step back and ask yourself what the task is and provide more context to get a better help for your question.
If all you want is to print some output to console, you could do it like (assuming the method findDifference returns a string):
Stream.of(firstFileLog, second)
.flatMap (Collection::stream)
.collect(Collectors.groupingBy(Logs::getId,
Collectors.mapping(Logs::getTime,Collectors.toList())))
.forEach((id,list) -> {
System.out.println(id + "="
+ list
+ (list.size() <2 ? " - ignore": ", diff: "+ findDifference(list.get(0), list.get(1))));
});
If you need the data for further processing there might be other approaches which are better suited for your reqierments. But it is hard to tell just by guessing, so you may want to include minimal-reproducible-example with the relevant classes and methods
You could replace the forEach in your stream to do the required operation:
(Assume static import of Collectors
Stream.of(firstFileLog, second)
.flatMap (Collection::stream)
.collect(groupingBy(Logs::getId, mapping(Logs::getTime, toList())))
.entrySet()
.forEach(entry -> {
System.out.print(entry);
List<Time> time = entry.getValue();
if(time.size()==2) {
System.out.print(findDifference(time.get(0), time.get(1)));
}
System.out.println();
};
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With