Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

stream list into a set

I am looking to refactor how I have used a stream in some of my code. The first example is how I currently have done it. The second example is what im trying to make it look like.

Set<String> results = new HashSet<String>();  someDao.findByType(type)             .stream()             .forEach(t-> result.add(t.getSomeMethodValue()) ); 

Could it look something like this? If so how do I make it do it?

Set<String> results = someDao.findByType(type)             .stream()             .collect(  /*  ?? no sure what to put here  */ ); 
like image 200
Robbo_UK Avatar asked Sep 16 '15 12:09

Robbo_UK


People also ask

How will you convert a list to a set?

Given a list (ArrayList or LinkedList), convert it into a set (HashSet or TreeSet) of strings in Java. We simply create an list. We traverse the given set and one by one add elements to the list. // Set to array using addAll() method.

Can we convert list to HashSet in Java?

There are four ways to convert ArrayList to HashSet :Using constructor. Using add() method by iterating over each element and adding it into the HashSet. Using addAll() method that adds all the elements in one go into the HashSet. Using stream.

Can you Stream a set Java?

Being a type of Collection, we can convert a set to Stream using its stream() method.


1 Answers

Use Collectors.toSet :

Set<String> results = someDao.findByType(type)         .stream()         .map(ClassName::getValue)         .collect(Collectors.toSet()); 
like image 146
Eran Avatar answered Sep 24 '22 21:09

Eran