Recently I came across the new syntax of Java 8 that can be used to convert a list to a set:
Set<Integer> myset = mylist.stream().collect(Collectors.toSet()));
I would like to know the advantage of using this approach to convert a list to a set over the traditional way (by passing it as a argument to HashSet.)
The advantage is that it then becomes easier (or more accurately, requires fewer syntactical changes) to perform other functional operations at the same time.
Say later on you just wanted the even numbers in the set, you could then do that trivially with a filter:
Set<Integer> myset = mylist.stream()
.filter(p -> p%2==0)
.collect(Collectors.toSet());
If you'd done it the traditional way, then you'd either need to convert it to the above syntax, or write an additional loop to go through and pull out only the values that you wanted.
(This doesn't mean it's always better - there may be cases where you want to discourage someone changing the code at a later date to filter out values, in which case you could argue the traditional way is still preferable.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With