Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting list to set using java 8

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.)

like image 581
Tushar Banne Avatar asked Jan 04 '23 01:01

Tushar Banne


1 Answers

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.)

like image 124
Michael Berry Avatar answered Jan 05 '23 15:01

Michael Berry