从单个arraylist获取多个列表

Dev*_*vGo 1 java arraylist

我需要使用特定对象的属性(Location)获取多个对象列表(Student),代码如下所示,

   List<Student> studlist = new ArrayList<Student>();
    studlist.add(new Student("1726", "John", "New York"));
    studlist.add(new Student("4321", "Max", "California"));
    studlist.add(new Student("2234", "Andrew", "Los Angeles"));
    studlist.add(new Student("5223", "Michael", "New York"));
    studlist.add(new Student("7765", "Sam", "California"));
    studlist.add(new Student("3442", "Mark", "New York"));
Run Code Online (Sandbox Code Playgroud)

我根据位置需要3个单独的列表.

1.Newyork list 2.California list 3.Los Angeles list

谁能在这里告诉我正确的方法?提前致谢.

was*_*ren 5

像这样的简单Java 8构造可以解决这个问题:

final Map<String, List<Student>> byLocation = 
    studlist.stream().collect(Collectors.groupingBy(Student::getLocation));
Run Code Online (Sandbox Code Playgroud)

这将创建一个Map<String, List<Student>>包含三个列表并使用locationas键的键(假设Student类具有getLocation-method).

要检索"纽约"列表,只需使用byLocation.get("New York").要简单地使用所有列表byLocation.values(),您将获得Collection<List<Student>>包含列表的列表.