统计List中指定属性不同值的出现的次数

(166) 2024-04-25 15:01:01

package domain;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class CoutName {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Entiy entiy=new Entiy();
		List<Entiy> list=new ArrayList<>();
		entiy.setName("123455");
		list.add(entiy);
		Entiy entiy1=new Entiy();
		entiy1.setName("123455");
		list.add(entiy1);
		Entiy entiy2=new Entiy();
		entiy2.setName("123455");
		list.add(entiy2);
		Entiy entiy3=new Entiy();
		entiy3.setName("1234");
		list.add(entiy3);
		Entiy entiy4=new Entiy();
		entiy4.setName("1234");
		list.add(entiy4);
		Entiy entiy5=new Entiy();
		entiy5.setName("12345");
		list.add(entiy5);
		Entiy entiy6=new Entiy();
		entiy6.setName("12345");
		list.add(entiy6);
		System.out.println(list);
		
		Map<String ,Long> map=list.stream().collect(Collectors.groupingBy(doc -> doc.getName(),Collectors.counting()));
		
		map.forEach((k,v) ->{
			System.out.println(k+":"+v);
		});
	}
	

}
package domain;

public class Entiy {
	String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@Override
	public String toString() {
		return "Entiy [name=" + name + "]";
	}
	
}

 

THE END

发表回复