【发布时间】:2019-07-28 18:51:37
【问题描述】:
我有一个问题,我想创建一个新的数组列表,因为必须将它发送到其他类。
我无法发布我原来的问题,所以复制了数据。
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Grouping {
List<Student> studlist1 = new ArrayList<Student>();
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
List<Student> studlist = new ArrayList<Student>();
studlist.add(new Student("1", "John", "New York"));
studlist.add(new Student("1", "Max", "California"));
studlist.add(new Student("2", "Andrew", "Los Angeles"));
studlist.add(new Student("3", "Michael", "New York"));
studlist.add(new Student("3", "Sam", "California"));
studlist.add(new Student("4", "Mark", "New York"));
Map<String, List<Student>> groupedStudents = new HashMap<String, List<Student>>();
for (Student student: studlist) {
String key = student.stud_id;
if (groupedStudents.containsKey(key)) {
List<Student> list = groupedStudents.get(key);
list.add(student);
}
else {
List<Student> list = new ArrayList<Student>();
list.add(student);
groupedStudents.put(key, list);}
}
Set<String> groupedStudentsKeySet = groupedStudents.keySet();
int index = 0;
for (String id: groupedStudentsKeySet) {
List<Student> stdnts = groupedStudents.get(id);
for (Student student : stdnts) {
// Want to create a new arraylist as belows.Grouing data in arraylist according to same ID
// arraylist will be as
//
// index 0: 1,John,New York,Max,Califoornia
// index 1: 2, Andrew, Los Angeles
// index 2: 3,Michael, New York, "Sam", California
// index 3: 4,Mark, New York
}
}
}
}
class Student {
String stud_id;
String stud_name;
String stud_location;
Student(String sid, String sname, String slocation) {
this.stud_id = sid;
this.stud_name = sname;
this.stud_location = slocation;
}
}
想创建一个新的arraylist,如下所示。根据相同的ID对arraylist中的数据进行分组
Arraylist 应该是 索引 0:1,约翰,纽约,马克斯,加利福尼亚
索引 1:2,安德鲁,洛杉矶
索引 2:3,迈克尔,纽约,“山姆”,加利福尼亚
索引 3:4,马克,纽约
只想要和上面一样的数组列表
【问题讨论】:
-
问题的任何解决方案
标签: java arraylist collections