从单个arraylist获取多个列表

时间:2014-12-26 11:06:12

标签: 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"));

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

1.Newyork名单 2.加利福尼亚州名单 3.洛杉矶名单

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

5 个答案:

答案 0 :(得分:5)

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

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

这将创建一个包含三个列表的Map<String, List<Student>>,并使用location作为键(假设Student类具有getLocation - 方法)。

要检索&#34;纽约&#34; -list,只需使用byLocation.get("New York")即可。要获取所有列表,只需使用byLocation.values()即可获得包含列表的Collection<List<Student>>

答案 1 :(得分:1)

使用Java 8:

List<Student> nyList = studlist.stream()
    .filter(s -> "New York".equals(s.getLocation()))
    .collect(Collectors.toList());

List<Student> caList = studlist.stream()
    .filter(s -> "California".equals(s.getLocation()))
    .collect(Collectors.toList());

List<Student> laList = studlist.stream()
    .filter(s -> "Los Angeles".equals(s.getLocation()))
    .collect(Collectors.toList());

答案 2 :(得分:0)

您应该使用城市作为关键字的HashMap包装,因此您可以根据他们的城市对学生进行分组,例如

Map<String, List<Student>> studMap = new HashMap<String, List<Student>>();

答案 3 :(得分:0)

假设您的班级学生将位置存储在 loc 中。

  ArrayList<Student> newyorkList = new  ArrayList<Student>();

 ArrayList<Student> californiaList = new  ArrayList<Student>();

 ArrayList<Student> losangelesList = new  ArrayList<Student>();

for(int i = 0; i< studlist.size();i++){
      Student temp = (Student) studlist.get(i);

       If( (temp.loc).equals("New York") )
                  newyorkList.add(temp);

       If( (temp.loc).equals("California") )
                  californiaList.add(temp);

       If( (temp.loc).equals("Los Angeles") )
                  losangelesList.add(temp);

  }

答案 4 :(得分:0)

您可以使用Google Guava Collections:

ListMultimap<String, Student> map = ArrayListMultimap.create();
for (Student student : studlist)
    map.put(student.getLocation(), student);

然后你可以通过

获得纽约List
List<Student> newYorkers = map.get("New York");

如果您没有使用Java 8或Google Guava Collections,我认为您可以做得比这更好:

Map<String, List<Student>> map = new HashMap<String, List<Student>>();
for (Student student : studlist) {
    String location = student.getLocation();
    List<Student> list = map.get(location);
    if (list == null) {
        list = new ArrayList<Student>();
        map.put(location, list);
    }
    list.add(student);
}