I want to find the number of dates from 1st week, 2nd week, 3 rd week and 4th week from the given dates list
[2017-11-22 21:41:39.0, 2017-11-27 23:15:26.0, 2017-11-27 23:26:23.0,
2017-11-28 19:50:18.0, 2017-11-29 16:14:33.0] are dates
//By Using map
Map<Integer, List<Date>> map;
map = inboxOutboxentityList.stream()
.collect(Collectors.groupingBy(element ->
element.getDate().get(weekFields.weekOfWeekBasedYear())
)
);
If you can, just forget about the long outdated Date
class and solve your problem in pure java.time
. Your code is not far from working.
List<LocalDateTime> entities = Arrays.asList(
LocalDateTime.of(2017, Month.NOVEMBER, 22, 21, 41, 39),
LocalDateTime.of(2017, Month.NOVEMBER, 27, 23, 15, 26),
LocalDateTime.of(2017, Month.NOVEMBER, 27, 23, 26, 23),
LocalDateTime.of(2017, Month.NOVEMBER, 28, 19, 50, 18),
LocalDateTime.of(2017, Month.NOVEMBER, 29, 16, 14, 33));
Map<Integer, Long> countPerWeek = entities.stream()
.collect(Collectors.groupingBy(
ldt -> ldt.get(WeekFields.ISO.weekOfWeekBasedYear()),
Collectors.counting()));
System.out.println(countPerWeek);
This prints:
{48=4, 47=1}
So the count is 1 for week 47 and 4 for week 48. I believe this was what you intended. Please substitute a different WeekFields
object if required.
If you are getting a list of Date
objects, you will need to convert them into some modern class first. There are plenty of questions and answers about how to do that, happy searcing. As you have probably already realized, you can do it in the same series of stream operations.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.