在列表中保留非重复的条目

在列表中保留非重复的条目

本文介绍了在列表中保留非重复的条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有对象列表.假设对象的结构如下.

I have list of objects. Assuming the structure of object is as follows.

class Test {
   Int id;
   String y;
}

给出一个带有四个Test实例的列表"testList"(我们将其称为t1,t2,t3,t4).

Given a list 'testList' with four instances of Test (let's call them t1, t2, t3, t4).

要求是获取一个列表,其中仅保留字段"y"是唯一的项目.每个具有重复值的条目都应删除.

Requirement is to obtain a list where only the items where the field 'y' is unique are retained.Each entry which has a duplicated value should be removed.

在上述情况下,假设t3和t4包含相同的"y"值,则结果应为t1和t2.

In the above case, assuming that t3 and t4 contains the same value of 'y', the result should be t1 and t2.

一种解决方案是首先创建一个哈希映射:

One solution is to first create a hash map:

  Map<String, List<Test>> yTestMap = new HashMap();

并使用该字段作为键,添加与该键匹配的每个对象

and use the field as key, adding each object that matches the key

然后遍历HashMap条目集,并在值列表包含多个元素的位置将那些Test实例从实际列表中删除.

Then loop through the HashMap entry set and where ever the value list contains more than one element remove those Test instances from the actual list.

for (List<Test> duplicateTestList : yTestMap.values())
{
     testList.removeAll(duplicateTestList);
}

能否请您提出一种更简洁的方法,例如使用Java 8流?

Could you please suggest a more coincise way, maybe using Java 8 streams?

推荐答案

,您可以使用Set and Comparable.在使用它之前,您应该在测试中实现Comparable.

you can use Set and Comparable.Before using it you should implements Comparable in Test.

import java.util.*;

public class Test implements Comparable<Test>{
 private int id;
 private String y;

 @Override
 public int compareTo(Test test){
   return y.compareTo(test.getY());
 }

 public void setY(String newY){
   y = newY;
 }

 public void setId(int newId){
   id = newId;
 }

 public String getY(){
   return y;
 }

 public String toString(){
  return "Id: " + id + "\nValue of Y: " + y + "\n";
 }
}

Set中不允许重复的值.

Duplicate values are not allowed in Set.

import java.util.*;

public class Main{

 public static void main(String arg[]){
    Set<Test> testList = new TreeSet<Test>();

    Test t0 = new Test();
    t0.setId(0);
    t0.setY("Y0");

    Test t1 = new Test();
    t1.setId(1);
    t1.setY("Y1");

    Test t2 = new Test();
    t2.setId(2);
    t2.setY("Y1");//here you can see same 'Y' value of t1

    testList.add(t0);
    testList.add(t1);
    testList.add(t2);

    //t0 and t1 will be printed. t2 has duplicated Y-value so it's
    // not included
    testList.forEach(e -> System.out.println(e));
}

}

这篇关于在列表中保留非重复的条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 07:17