java stream filter map collect

Solutions on MaxInterview for java stream filter map collect by the best coders in the world

showing results for - "java stream filter map collect"
Jana
21 Jan 2017
1// Creates a list of ProgrammingLanguage objects,
2// maps it with a method of ProgrammingLanguage to get the name
3// and filters them for programming languages, which are not starting with C.
4
5
6import java.util.List;
7import java.util.Arrays;
8import java.util.stream.Collectors;
9
10
11class ProgrammingLanguage {
12
13    private String name = "";
14
15    public static void main(final String args[]) {
16        List<ProgrammingLanguage> programmingLanguages = Arrays.asList(
17                new ProgrammingLanguage("Java"),
18                new ProgrammingLanguage("Python"),
19                new ProgrammingLanguage("C#"),
20                new ProgrammingLanguage("JS"),
21                new ProgrammingLanguage("C++"),
22                new ProgrammingLanguage("C"));
23        List<String> nonCProgrammingLanguages = programmingLanguages.stream()  // creates stream from list
24                .map(ProgrammingLanguage::getName)
25                .filter(name -> !name.startsWith("C"))
26                .collect(Collectors.toList());  // convert stream back to list
27        System.out.println("Names not starting with C: " + nonCProgrammingLanguages);
28    }
29
30
31    public ProgrammingLanguage(final String name) {
32        setName(name);
33    }
34
35
36    public String getName() {
37        return name;
38    }
39
40    public void setName(final String name) {
41        this.name = name;
42    }
43}