Use Stream # collect to retrieve and list only specific fields from a JavaBean list

Use the following Hoge class as a sample.

public class Hoge {

    private String foo;

    private String bar;

    public Hoge(String foo, String bar) {
        this.foo = foo;
        this.bar = bar;
    }

    // getter/setter
}

Use Stream # collect to create a list of Hoge # bar.

//Create Hoge list
List<Hoge> hoges = Arrays.asList(new Hoge("f001", "b001")
                               , new Hoge("f002", "b002")
                               , new Hoge("f003", "b003"));
// Hoge#Create a list of bars
List<String> bars = hoges.stream().collect(ArrayList::new
                                        , (l, h) -> l.add(h.getBar())
                                        , (l1, l2) -> l1.addAll(l2));

System.out.println(bars); // [b001, b002, b003]

Recommended Posts

Use Stream # collect to retrieve and list only specific fields from a JavaBean list
Scraping and writing specific elements to a file
[Java] How to erase a specific character from a character string
Ruby Regular Expression Extracts from a specific string to a string
Extract a specific element from the list of objects
[IOS] To allow rotation of only a specific screen
I want to make a list with kotlin and java!
[Rails] Function to search and list products from multi-level categories
[ruby] Creating a program that responds only to specific conditions
[Controller] I want to retrieve the numerical value of a specific column from the DB (my memo)