java怎么找出一个list或者set其中相同的项并进行分组

java怎么找出一个list或者set其中相同的项并进行分组

很简单 使用map的containsKey方法即可实现 废话不多说 直接贴代码 新手也能看懂

Student类

package test1;

public class Student {
	private int groupId;
	private String name;
	public int getGroupId() {
		return groupId;
	}
	public void setGroupId(int groupId) {
		this.groupId = groupId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Student(int groupId, String name) {
		super();
		this.groupId = groupId;
		this.name = name;
	}
	@Override
	public String toString() {
		return "Student [groupId=" + groupId + ", name=" + name + "]";
	}
	
	
}

demo演示

package test1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class test8 {
	
	public static void main(String[] args) {
		Student s1 = new Student(1,"小明");
		Student s2 = new Student(1,"小李");
		Student s3 = new Student(1,"小张");
		Student s4 = new Student(3,"小光");
		Student s5 = new Student(2,"小虎");
		Student s6 = new Student(2,"小都");
		Student s7 = new Student(3,"小哦");
		Student s8 = new Student(1,"小高");
		Student s9 = new Student(2,"小人");
		
		List<Student> list = Arrays.asList(s1,s2,s3,s4,s5,s6,s7,s8,s9);
		
		HashMap<Integer,List<Student>> map = new HashMap<Integer,List<Student>>();
		for (Student student : list) {
			if(map.containsKey(student.getGroupId())) {
				List<Student> oldSL = map.get(student.getGroupId());
				oldSL.add(student);
				map.put(student.getGroupId(), oldSL);
			}else {
				ArrayList<Student> newSL = new ArrayList<>();
				newSL.add(student);
				map.put(student.getGroupId(), newSL);
			}
			
		}
		System.out.println(map);
	}

}

最后打印结果
java怎么找出一个list或者set其中相同的项并进行分组_第1张图片
java怎么找出一个list或者set其中相同的项并进行分组_第2张图片
java怎么找出一个list或者set其中相同的项并进行分组_第3张图片

你可能感兴趣的:(文章列表)