I'm trying to learn the Java Set
interface and have encountered the following code online, I understand the purpose of this code is to convert a Collection<Object>
to a TreeSet
, but I do not understand how the statement works because the syntax is complex and foreign to me. Could someone walk me through the process step by step?
Set<String> set = people.stream()
.map(Person::getName)
.collect(Collectors.toCollection(TreeSet::new));
And also, under what kind of circumstances should we prefer the above syntax over the one below?
Set<Integer> s1 = new TreeSet(c1); //where c1 is an instance of Collection interface type