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

来源:互联网 发布:双十一成交额最新数据 编辑:程序博客网 时间:2024/06/15 23:32

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

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> * @date2017-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++;}}//如果有两条重复数据添加到MAPif(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 {//主键 IDprivate 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;}}


1 0
原创粉丝点击