Streams & Reductions
Java Swing
Other
100

For each of these stream functions, indicate whether it is terminal or intermediary:

1. map()

2. findAny()

3. limit()

4. distinct()

1. map() => intermediate

2. findAny() => terminal

3. limit() => intermediate

4. distinct() => intermediate

100

What does GUI stand for?

Graphical User Interface

100

[Comeback Question]

Using recursion, write a function that counts the number of times the letter "e" appears in a String

public static void countE(String s) {

    if (s.isEmpty()) { return 0; }

    int firstCount = s.charAt(0) == "e" ? 1 : 0;

    return firstCount + countE(s.substring(1));

}

200

What is the value of "result" after this code runs:

List<String> words = List.of("a", "b" "aa", "bb", "abc");

long result = words.stream()

    .map(w -> w.length())

    .distinct()

    .count();

3

200

What are the 5 regions supported by BorderLayout?

NORTH, SOUTH, EAST, WEST, CENTER

200

[Blue Shell]

You have the following code, which calls an unknown function findItem():

Optional<String> result = findItem();

Write some code that prints out "No item was found" if result is empty, or the result if one was returned.

System.out.println(result.orElse("No item was found));

300

[Comeback Question]
A Planet class includes getters and setters for numMoons (int) and name (String).

Using streams, write some code that that takes a list of Planets and creates a list of the names of the planets that have at least 2 moons.

planets.stream()

    .filter(p -> p.getNumMoons() >= 2)

    .map(p -> p.getName())

    .collect(Collectors.toList());

300

In programs like Paint where you are drawing custom shapes, what class do you likely want to extend, and what function do you need to implement?

JPanel

paintComponent(Graphics g)

^ you get credit even if you didn't include Graphics g

300

[Comeback Question]

int x = 6; int y = 7;

int z = (x < y && y < 8) ? -1 : 1;

What is z?

-1

400

Using streams, write code that takes a list of Strings and produces a String containing the concatenated first letters of each String.

e.g. words.stream()...

One possible solution:

words.stream()

    .reduce("", (a, w) -> a + w.charAt(0));

400

Write a class for a custom Swing component that contains two side-by-side text fields. The constructor should take in the contents of the two text fields.

You may want to reference some of the following classes:

JFrame, JPanel, JLabel, JButton, JTextField

[Code may vary]

400

Collection<String> list = List.of("mercury", "valkyrie", "sky");

XXXXX result = list.stream().sorted(

    (a, b) -> a.charAt(1) - b.charAt(1))

    .findFirst().get();

 What type and value does result have?

String, "Valkyrie"

M
e
n
u