使用单独的收集流过滤

时间:2016-10-10 06:46:01

标签: java collections java-8 java-stream

我有人名单&每个人都有人的类型,即10,11,12

我想制作每个人类型

的子列表

使用Streams,我已经实现了3次迭代

可以分组&进入1次迭代?

Person.java

public class Person {

    String personType;
    String name;

    public Person(String personType, String name) {
        this.personType = personType;
        this.name = name;
    }

    public String getPersonType() {
        return personType;
    }

    public void setPersonType(String personType) {
        this.personType = personType;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Person{" +
                "personType='" + personType + '\'' +
                ", name='" + name + '\'' +
                '}';
    }
}

Driver.java

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Driver {

    public static void main(String[] args) {

        List<Person> persons = populateList();

         List<Person> persons1 =  persons.stream().filter( p -> p.getPersonType().equals("10")).collect(Collectors.toList());
        List<Person> persons2 =  persons.stream().filter( p -> p.getPersonType().equals("10")).collect(Collectors.toList());
        List<Person> persons3 =  persons.stream().filter( p -> p.getPersonType().equals("10")).collect(Collectors.toList());

    }
    public static List<Person> populateList(){
            Person person01 = new Person("10","Tony");
            Person person02 = new Person("11","Steve");
            Person person03 = new Person("12","Banner");
            Person person04 = new Person("10","Thor");
            Person person05 = new Person("11","Natasha");
            Person person06 = new Person("12","Loki");
            Person person07 = new Person("10","Peter");
            Person person08 = new Person("11","HawkEye");
            Person person09 = new Person("12","Falcon");
            Person person10 = new Person("10","Jarvis");
        List<Person> persons = new ArrayList<>();
            persons.add(person01);
            persons.add(person02);
            persons.add(person03);
            persons.add(person04);
            persons.add(person05);
            persons.add(person06);
            persons.add(person07);
            persons.add(person08);
            persons.add(person09);
            persons.add(person10);
        return persons;
    }
}

1 个答案:

答案 0 :(得分:3)

您可以使用group by。

Map<String, List<Person>> obj1 = persons.stream().collect(Collectors.groupingBy(Person :: getPersonType));
System.out.println(obj1);