stream list into a set

51,762

Use Collectors.toSet :

Set<String> results = someDao.findByType(type)
        .stream()
        .map(ClassName::getValue)
        .collect(Collectors.toSet());
Share:
51,762

Related videos on Youtube

Robbo_UK
Author by

Robbo_UK

Updated on July 09, 2022

Comments

  • Robbo_UK
    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.
      Alexis C. over 8 years
      You need to map the Stream elements before collecting them into the Set. someDao.findByType(type) .stream().map(TheClass::getValue).collect(toSet());