fork(4) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.text.SimpleDateFormat;
  7. import java.time.temporal.ChronoUnit;
  8. import java.util.stream.Collectors;
  9.  
  10. /* Name of the class has to be "Main" only if the class is public. */
  11. class Ideone
  12. {
  13. public static void main (String[] args) throws java.lang.Exception{
  14.  
  15. SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
  16. List<Entry> list = Arrays.asList(new Entry(sdf.parse("2011-03-21 09:00"), "VALUE1")
  17. , new Entry(sdf.parse("2011-03-21 09:00"), "VALUE2")
  18. , new Entry(sdf.parse("2011-03-22 09:00"), "VALUE3")
  19. , new Entry(sdf.parse("2011-03-22 09:00"), "VALUE4")
  20. , new Entry(sdf.parse("2011-03-21 09:00"), "VALUE5")
  21. );
  22.  
  23. Map<Date, List<Entry>> entries = list.stream().collect(Collectors.groupingBy(e ->
  24. // easier way to truncate the date
  25. Date.from(e.getDate().toInstant().truncatedTo(ChronoUnit.DAYS)),TreeMap::new, Collectors.toList()) //added treemap to sort by keys
  26. );
  27.  
  28. //--- printing---
  29.  
  30. SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  31. format.setTimeZone(TimeZone.getTimeZone("GMT")); // using GMT timezone to avoid inconsistencies when printing
  32.  
  33. entries.forEach((date, entries1) -> {
  34. System.out.println(format.format(date));
  35. entries1.forEach(entry -> System.out.println("\t" + entry.getValue()));
  36. });
  37. }
  38. }
  39.  
  40. class Entry {
  41. private final Date date;
  42. private final String value;
  43.  
  44. public Entry(Date date, String value) {
  45. this.date = date;
  46. this.value = value;
  47. }
  48.  
  49. public Date getDate() {
  50. return date;
  51. }
  52.  
  53. public String getValue() {
  54. return value;
  55. }
  56.  
  57. @Override
  58. public String toString() {
  59. return "Entry{" +
  60. "date=" + date +
  61. ", value='" + value + '\'' +
  62. '}';
  63. }
  64. }
Success #stdin #stdout 0.26s 35996KB
stdin
Standard input is empty
stdout
2011-03-21
	VALUE1
	VALUE2
	VALUE5
2011-03-22
	VALUE3
	VALUE4