Library method to partition a collection by a predicate

前端 未结 6 716
小鲜肉
小鲜肉 2020-12-29 21:02

I have a collection of objects that I would like to partition into two collections, one of which passes a predicate and one of which fails a predicate. I was hoping there wo

6条回答
  •  猫巷女王i
    2020-12-29 21:59

    Note that in case of limited set of known in advance partiotion keys it may be much more efficient just to iterate the collection once more for each partition key skipping all different-key items on each iteration. As this would not allocate many new objects for Garbage Collector.

    LocalDate start = LocalDate.now().with(TemporalAdjusters.firstDayOfYear());
    LocalDate endExclusive = LocalDate.now().plusYears(1);
    List daysCollection = Stream.iterate(start, date -> date.plusDays(1))
            .limit(ChronoUnit.DAYS.between(start, endExclusive))
            .collect(Collectors.toList());
    List keys = Arrays.asList(DayOfWeek.values());
    
    for (DayOfWeek key : keys) {
        int count = 0;
        for (LocalDate day : daysCollection) {
            if (key == day.getDayOfWeek()) {
                ++count;
            }
        }
        System.out.println(String.format("%s: %d days in this year", key, count));
    }
    

    Another both GC-friendly and encapsulated approach is using Java 8 filtering wrapper streams around the original collection:

    List>> partitions = keys.stream().map(
            key -> new AbstractMap.SimpleEntry<>(
                    key, daysCollection.stream().filter(
                        day -> key == day.getDayOfWeek())))
            .collect(Collectors.toList());
    // partitions could be passed somewhere before being used
    partitions.forEach(pair -> System.out.println(
            String.format("%s: %d days in this year", pair.getKey(), pair.getValue().count())));
    

    Both snippets print this:

    MONDAY: 57 days in this year
    TUESDAY: 57 days in this year
    WEDNESDAY: 57 days in this year
    THURSDAY: 57 days in this year
    FRIDAY: 56 days in this year
    SATURDAY: 56 days in this year
    SUNDAY: 56 days in this year
    

提交回复
热议问题