简体   繁体   中英

Transforming a List of POJO into a List strings based on Two Properties of each object

I have the following POJO:

public class Alpha {

    String exp1;
    String exp2;

    public Alpha(String exp1, String exp2) {
        super();
        this.exp1 = exp1;
        this.exp2 = exp2;
    }

    public String getExp1() {
        return exp1;
    }

    public String getExp2() {
        return exp2;
    }

}

The main() method:

public static void main(String[] args) {
    SpringApplication.run(Main.class, args);

    Alpha alpha1 = new Alpha("patrol", "amazon");
    Alpha alpha2 = new Alpha("converse", "funky");
    List<Alpha> list = Arrays.asList(alpha1, alpha2);

    List<String> collect = list.stream()
        .map(Alpha::getExp1)
        .collect(Collectors.toList());

    System.out.println(collect);

}

It produces the output:

[patrol, converse]

The desired output should look like:

[patrol, converse, patrol, amazon]

Question is how to obtain with using only a single stream?

You can achieve it by using flatMap() :

Alpha alpha1 = new Alpha("patrol", "amazon");
Alpha alpha2 = new Alpha("converse", "funky");
List<Alpha> list = Arrays.asList(alpha1, alpha2);
    
List<String> collect = list.stream()                               // Stream<Alpha>
    .flatMap(alpha -> Stream.of(alpha.getExp1(), alpha.getExp2())) // Stream<String>
    .collect(Collectors.toList());
        
System.out.println(collect);

Output:

[patrol, amazon, converse, funky]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM