Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java Introduction to Functional Programming Reduction and Aggregation Using a Range to Produce a Menu

How to produce a menu using the range function?

I have been working on this problem for quite some time and I just can't figure it out?

1 Answer

Michael Switzer
Michael Switzer
7,489 Points

This was a real struggle for me too. Here is what I finally ended up with:

  public static List<String> getStateCodesFromRecords(List<HousingRecord> records) {
    return records.stream()
      // TODO: Map the stream to the state code
      .map(HousingRecord::getState)
      // TODO: Filter out any records without a state
      .filter(state -> !state.isEmpty())
      // TODO: There are duplicate state codes in the records, make sure we have a unique representation
      .distinct()
      // TODO: Sort them alphabetically
      .sorted()
      // TODO: Collect them into a new list.
      .collect(Collectors.toList());
  }
  public static void displayStateCodeMenuDeclaratively(List<String> stateCodes) {
    // TODO: Use a range to display a numbered list of the states, starting at 1.
    IntStream.rangeClosed(1, stateCodes.size())
      .mapToObj(count -> String.format("%d. %s", count, stateCodes.get(count - 1)))
      .forEach(System.out::println);
  }