Sets

A set holds each value only once, and HashSet, LinkedHashSet and TreeSet differ in the order they give back the values.

Journeyman · Java · Updated

By

Sets have similar functionality to lists with a few distinct differences.

  1. Sets cannot contain duplicate values
  2. The order of the values depends on the type of set
  3. Set values cannot be accessed by their ordinal position, only by iterating through each value
  4. There are three types of sets:
    • HashSet - no particular order (set by each value's hash)
    • LinkedHashSet - the order the values were added
    • TreeSet - sorted in natural order (alphabetical for strings)
Set<String> weekdays = new HashSet<>();

weekdays.add("Sunday");
weekdays.add("Monday");
weekdays.add("Tuesday");
weekdays.add("Wednesday");
weekdays.add("Thursday");
weekdays.add("Friday");
weekdays.add("Saturday");

weekdays.forEach(day -> System.out.println(day));

Sets are ordered based on the set type

Do it: the party's guest lists, without repeats

Friends reply to a party invitation by text, and some reply twice ("Yes!" then "Still coming!"). The host wants two lists of the guests, each name only once: one in the order people first replied, to thank them in that order, and one in alphabetical order, for the name cards at the door.

Both methods get one value:

  • replies: the name on each reply, a List<String>, in the order the replies came in. A name can be on it more than once.

For example, with these replies:

List<String> replies = List.of("Olivia", "Ethan", "Sophia", "Ethan", "Liam", "Olivia");
Method It returns
guestsInReplyOrder(replies) a set holding Olivia, Ethan, Sophia, Liam, in that order
guestsInAlphabeticalOrder(replies) a set holding Ethan, Liam, Olivia, Sophia, in that order

Either way, there are 4 guests, not 6: Ethan and Olivia each count once.

Your job: write the two methods. Each returns a Set<String>.

  • guestsInReplyOrder(List<String> replies): each name once, in the order it first appears in replies.
  • guestsInAlphabeticalOrder(List<String> replies): each name once, in alphabetical order.
  • Choose the kind of set that gives each order by itself, with no sorting of your own.
  • When there are no replies (an empty list), each returns an empty set.

Practiced live on the lesson page: write the Java right there and check it.

Cheat sheets