Reputation: 1725
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.)
Upvotes: 4
Views: 25271
Reputation: 341
You can simply use this precise code:
Set<Integer> myset = new HashSet<>(mylist);
and that's it.
Upvotes: 1
Reputation: 935
Please find below code to concert List to Set using stream API of Java 8:
package streamapi;
import java.util.*;
import java.util.stream.Collector;
import java.util.stream.Collectors;
class Person{
int empid;
String name;
Person(int empid,String name){
this.empid = empid;
this.name = name;
}
public String toString(){
return "id"+this.empid+"name"+this.name;
}
public boolean equals(Object obj) {
Person p = (Person)obj;
if(p.empid==this.empid && p.name.equals(this.name)) {
return true;
}
return false;
}
public int hashCode() {
return this.empid+this.name.hashCode();
}
}
public class collectionFilter {
public static void main(String[] args) {
List<Person> list = new ArrayList();
list.add(new Person(101,"aaa"));
list.add(new Person(200,"bbbb"));
list.add(new Person(150,"ccccc"));
list.add(new Person(250,"ddddd"));
list.add(new Person(250,"ddddd"));
converListToSet(list);
}
public static void converListToSet(List<Person> list) {
Set<Person> set = list.stream()
.collect(Collectors.toSet());
set.forEach(person->System.out.println(person));
}
}
Output like this:
id200namebbbb
id101nameaaa
id150nameccccc
id250nameddddd
Upvotes: 1
Reputation: 72254
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.)
Upvotes: 11