import java.util.*; import java.util.stream.Collectors; public class StreamExample { private static class HW1Date { int day; int month; int year; HW1Date(int day, int month, int year) { this.day = day; this.month = month; this.year = year; } public String toString() { return "day: " + day + " month: " + month + " year: " + year; } } public static void main(String[] args) { /* * 4. * * Write a function dates_in_month that takes a list of dates and a month * (i.e., an int) and returns a list holding the dates from the argument list * of dates that are in the month. * * The returned list should contain dates in the order they were originally given. * * Let's try this without using the stream API... */ List dates = Arrays.asList(new HW1Date[] { new HW1Date(1, 1, 1500), new HW1Date(2, 2, 1900), new HW1Date(10, 4, 3104), new HW1Date(20, 7, 2004) }); // With no stream API for (HW1Date d : datesInMonthNoStream(dates, 2)) { System.out.println(d); } // With the stream API! Instead of using a for each loop, we can instead use the .forEach // function introduced in the Collection interface! datesInMonthStream(dates, 2).forEach(d -> System.out.println(d)); // But hm... the above method looks a lot like function wrapping though. Instead, we can actually // use method references! 'System.out' is an object that has a 'println' method. Thus, we can actually just // say this instead: datesInMonthStream(dates, 2).forEach(System.out::println); } public static List datesInMonthNoStream(List dates, int month) { List res = new ArrayList<>(); for (HW1Date date : dates) { if (date.month == month) { res.add(date); } } return res; } // Neat, it's a single concise line! public static List datesInMonthStream(List dates, int month) { return dates.stream().filter(d -> d.month == month).collect(Collectors.toList()); } }