Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

149
Visualizações
Java - Collectors.groupingBy - the last 15 days

is it possible to group by the last 15 days using Java's Collectors.groupingBy?

Input:

public class Tweet { 

 String id;
 LocalDate createdAt; 

 // Constructor Ignored

 List<Tweet> tweets = new ArrayList(){{
  add(new Tweet("1", "2021-11-17"));
  add(new Tweet("2", "2021-11-16"));
  add(new Tweet("3", "2021-11-14"));
  add(new Tweet("4", "2021-11-13"));
  add(new Tweet("5", "2021-11-12"));
  add(new Tweet("7", "2021-10-09"));
  add(new Tweet("8", "2021-10-08"));
  add(new Tweet("9", "2021-10-07"));
  add(new Tweet("10", "2021-09-02"));
  add(new Tweet("11", "2021-09-01"));
 ...

 }};

}

Expected Output:

2021-11-17:  (group must include 2021-11-17 + 15 days before 17th)
 Tweet("1", "2021-11-17");
 Tweet("2", "2021-11-16");
 Tweet("3", "2021-11-14");
 Tweet("4", "2021-11-13");
 Tweet("5", "2021-11-12");

2021-10-09: (group to include 2021-10-09 + 15 days before 9th)
 Tweet("7", "2021-10-09");
 Tweet("8", "2021-10-08");
 Tweet("9", "2021-10-07");

2021-09-01: (group to include 2021-09-01 + 15 days before 1st)
Tweet("10", "2021-09-02");
Tweet("11", "2021-09-01");

Current logic (Not working):

Main Method:


TemporalAdjusters adjuster = TemporalAdjusters.ofDateAdjuster(d -> d.minusDays(15));

Map<LocalDate, List<Tweets>> groupByLast15Days = tweets.stream()
                .collect(Collectors.groupingBy(item -> item.createdAt())
                  .with(adjuster)));

System.out.println(groupByLast15Days);  // provides incorrect results

any help is massively appreciated! Thanks!

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You can get the day difference between two LocalDateTimes using ChronoUnit.DAYS.between(from,to) as stated here.

You can then divide this by 15 (so you have the same number for all days in that range):

LocalDate origin=LocalDate.now();
Map<LocalDate, List<Tweets>> groupByLast15Days = tweets.stream()
    .collect(Collectors.groupingBy(item-> 
       Long.valueOf(ChronoUnit.DAYS.between(item.createdAt(),origin)/15));

If you want to group by the start date, you can reverse the calculation (while the difference in between the 15 days is eliminated by the integer division):

LocalDate origin=LocalDate.now();
Map<LocalDate, List<Tweets>> groupByLast15Days = tweets.stream()
    .collect(Collectors.groupingBy(item -> 
        origin.plusDays(
            (ChronoUnit.DAYS.between(origin, item.createdAt()) /15)*15
        )
    ));

If you want to use TemporalAdjusters, you can do it like that:

LocalDate origin=LocalDate.now();
TemporalAdjusters adjuster = TemporalAdjusters.ofDateAdjuster(d ->
    origin.plusDays(
        (ChronoUnit.DAYS.between(origin, d) /15)*15
    )
);

Explainations:

Dividing an integer by another integer always yields an integer, even if the quotient would have decimal places. Integer division just removes those decimal places. If you divide a number by 15, it will return rhe same result for 15 consecutive numbers. After multiplying it with 15 again, you would get the first of those 15 numbers. Dividing a number by 15 and multiplying it with 15 again has the purpose that every 15 consecutive numbers are set to the same number (the first of those 15).

ChronoUnit.DAYS.between(date1, date2) just calculates the number of days between date1 and date2.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda