美文网首页
对象数组的重复项整理

对象数组的重复项整理

作者: 奶盐味小圆饼 | 来源:发表于2020-04-02 19:27 被阅读0次

    首先定义一个实体类Person, 两个属性编号和姓名.

    class Person {
        public Person(int id, String name) {
            this.id = id;
            this.name = name;
        }
    
        private int id;
    
        private String name;
    
        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 == null ? null : name.trim();
        }
    
        @Override
        public String toString() {
            return "Person{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    '}';
        }
    
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Person person = (Person) o;
            return id == person.id &&
                    Objects.equals(name, person.name);
        }
    
        @Override
        public int hashCode() {
            return Objects.hash(id, name);
        }
    

    然后给person数组赋值,这里我故意写了几个重复数据。

     private static final List<Person> persons = new ArrayList<Person>() {{
            add(new Person(1, "zhangsan1"));
            add(new Person(2, "zhangsan2"));
            add(new Person(3, "zhangsan3"));
            add(new Person(4, "zhangsan4"));
            add(new Person(1, "zhangsan1"));
            add(new Person(4, "zhangsan4"));
            add(new Person(3, "zhangsan3"));
            add(new Person(4, "zhangsan4"));
        }};
    

    最后在Main函数里对List数组进行去重处理

    public static void main(String[] args) {
            Map<Person, List<Integer>> indexes = new HashMap<>();
            for (int i = 0; i < persons.size(); i++) {
                indexes.computeIfAbsent(persons.get(i), c -> new ArrayList<>()).add(i);
            }
            System.out.println(indexes);
        }
    

    运行结果

    {Person{id=4, name='zhangsan4'}=[3, 5, 7], Person{id=3, name='zhangsan3'}=[2, 6], Person{id=2, name='zhangsan2'}=[1], Person{id=1, name='zhangsan1'}=[0, 4]}

    相关文章

      网友评论

          本文标题:对象数组的重复项整理

          本文链接:https://www.haomeiwen.com/subject/wwdfphtx.html