面试二 打印集合中重复记录 并显示重复次数

本文介绍了一种使用Java来检测列表中重复数据的方法。通过双重遍历列表,并利用HashMap来记录重复出现的数据及其出现次数,最后输出这些重复的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在面试过程中碰到的面试题,当时手写没有写出来,如果您有更好的方法,欢迎改进,程序如下:

package test;

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

import entity.Emp;

/**
 * @Description	测试类
 * @author		<p style="color:#8e8e8e;font-family:微软雅黑;font-size=16px;font-weight:bold;">Cloud</p>
 * @date		2017-2-9下午1:41:00
 */

public class TestEmp {

	/**
	 * @Description 检查集合中重复数据
	 * @author		<p style="color:#8e8e8e;font-family:微软雅黑;font-size=16px;font-weight:bold;">Cloud</p>
	 * @date		<p style="color:#000;font-family:微软雅黑;font-size=16px;">2017-2-9下午1:41:22</p> 
	 * @param args
	 */
	public static void main(String[] args) {
		//	实体数据初始化
		Emp emp1 = new Emp(1001, "张三", "9856741");
		Emp emp2 = new Emp(1002, "李四", "9856742");
		Emp emp3 = new Emp(1003, "王五", "9856741");
		Emp emp4 = new Emp(1004, "赵六", "9856742");
		Emp emp5 = new Emp(1005, "王八一", "9856745");
		Emp emp6 = new Emp(1005, "王八二", "9856745");
		Emp emp7 = new Emp(1005, "王八三", "9856742");
		Emp emp8 = new Emp(1005, "王八四", "9856745");
		
		//	填充数据
		List<Emp> empList = new ArrayList<Emp>();
		empList.add(emp1);
		empList.add(emp2);
		empList.add(emp3);
		empList.add(emp4);
		empList.add(emp5);
		empList.add(emp6);
		empList.add(emp7);
		empList.add(emp8);
		
		//	MAP	接收重复数据
		Map<String, Integer> dataMap = new HashMap<String, Integer>();
		
		//	循环集合数据
		for (int i = 0 ; i < empList.size() ; i++) {

			int count = 0 ;
			
			//	循环集合数据
			for (int j = 0 ; j < empList.size() ; j++) {
				//	判断是否重复
				if(empList.get(j).getAccount().equals(empList.get(i).getAccount())){
					count++;
				}
			}
			//	如果有两条重复数据	添加到MAP
			if(count >= 2){
				dataMap.put(empList.get(i).getAccount(), count);
			}

		}
		//	打印重复数据
		for (Map.Entry<String, Integer> empEntry : dataMap.entrySet()) {
			System.out.println(empEntry.getKey() + " 重复数次 " + empEntry.getValue());
		}
		System.out.println("-- success --");
	}
	
}

package entity;

public class Emp {
	
	//	主键 ID
	private int id;
	//	姓名
	private String name;
	//	帐号
	private String account;
	
	public Emp(){}

	public Emp(int id, String name, String account) {
		super();
		this.id = id;
		this.name = name;
		this.account = account;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

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

	public String getAccount() {
		return account;
	}

	public void setAccount(String account) {
		this.account = account;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值