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 */ );
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.
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.
Being a type of Collection, we can convert a set to Stream using its stream() method.
Use Collectors.toSet
:
Set<String> results = someDao.findByType(type) .stream() .map(ClassName::getValue) .collect(Collectors.toSet());
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