在面试过程中碰到的面试题,当时手写没有写出来,如果您有更好的方法,欢迎改进,程序如下:
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;
}
}