stream list into a set
51,762
Use Collectors.toSet
:
Set<String> results = someDao.findByType(type)
.stream()
.map(ClassName::getValue)
.collect(Collectors.toSet());
Related videos on Youtube
Author by
Robbo_UK
Updated on July 09, 2022Comments
-
Robbo_UK almost 2 years
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 */ );
-
Alexis C. over 8 yearsYou need to map the Stream elements before collecting them into the Set.
someDao.findByType(type) .stream().map(TheClass::getValue).collect(toSet());
-