通过使用哈希映射创建多个数组列表 [英] Create multiple Array lists by using Hashmap

查看:253
本文介绍了通过使用哈希映射创建多个数组列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为类学生,它有字符串属性日期。我有我的所有学生的名单,现在我想创建多个的ArrayList 这是由它们的日期分组

我想使用HashMap的:

  ArrayList的学生= getStudents();地图<弦乐,ArrayList的<的Student GT;> =新的HashMap<弦乐,ArrayList的<的Student GT;);为(我的学生:学生){
 //一定有什么东西
}

如何建立这是由它们的属性他们的字符串值分组学生多的ArrayList <?/ p>

解决方案

它使用Java 8最简单的方式流:

 地图&LT;字符串列表&LT;的Student GT;&GT;地图=
    students.stream()
            .collect(Collectors.groupingBy(学生:: GETDATE));

其中, GETDATE 学生类,通过它你希望组方法学生秒。

要完成pre-8的Java code答案:

 地图&LT;字符串列表&LT;的Student GT;&GT;地图=新的HashMap&LT;&GT;();
对于(学生小号:学生){
    清单&LT;的Student GT;清单= map.get(s.getDate());
    如果(名单== NULL){
        名单=新的ArrayList&LT;的Student GT;();
        map.put(s.getDate(),清单);
    }
    list.add(多个);
}

I have class named Student and it has String attribute date. I have list of all my Students and now I want to create multiple ArrayLists which are grouped by their dates.

I want to use hashmap:

ArrayList students = getStudents();

Map map<String, ArrayList<Student>> = new HashMap<String, ArrayList<Student>);

for (Student i: students) {
 // There must be something
}

How I can create multiple ArrayLists of Students which are grouped by their String value of their attribute?

解决方案

The easiest way it to use Java 8 Streams :

Map<String, List<Student>> map =
    students.stream()
            .collect(Collectors.groupingBy(Student::getDate));

Where getDate is the method of Student class by which you wish to group the Students.

To complete the answer for pre-Java 8 code:

Map<String, List<Student>> map = new HashMap<>();
for (Student s : students) {
    List<Student> list = map.get(s.getDate());
    if (list == null) {
        list = new ArrayList<Student>();
        map.put (s.getDate(), list);
    }
    list.add (s);
}

这篇关于通过使用哈希映射创建多个数组列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆