简体   繁体   中英

How to transform a list into a unique list?

So I have these two Classes, ParentClass and a ChildClass and I have these data(displayed on jTable):

Child Class       Parent Class
Child Class 1     Parent Class A
Child Class 2     Parent Class A
Child Class 3     Parent Class B
Child Class 4     Parent Class A
Child Class 3     Parent Class B
...               ... 

From this ChildClass View I am trying to get all parent class and put it into a Unique List/Set , because i will create a summary for this by saying Parent Class A has this total number of Child Class and I am doing like this:

List<ParentClass> parents = new ArrayList<ParentClass>();
...
for(ChildClass child : childs){
    ParentClassDaoImpl parentClassDaoImpl = new ParentClassDaoImpl();
    ParentClass parent = parentClassDaoImpl.findParent(child.getParentId());
    if(parents.isEmpty()){
        parents.add(parent);
    }else{
        if(parents.indexOf(parent) == -1){//I have to check if this parent is already on my lists
            parents.add(parent);
        }
    }
}
...

My problem is that I always get a duplicate list. I tried this but i get same output:

...
if (!parents.contains(parent)) {
    parents.add(parent);
}
...

By the way I am using 1.6 Java Version.

Every time you get new object of ParentClass thats why when ever you check that object is present in the list or not is always says that not present because it compare with reference of the object.

for maintain unique list of object either overried equels() method or just use Map<ParentClass Id, ParentClass object> and then just get map.values() method .

Instead of a List maybe you could manage a Map<ParentClass, Set<ChildClass>> ?

The key of your map would be the parent class, and the value would be a set of its children.

So you would iterate over all the children, and for each, you would simply call something like map.get(parent).add(child); Obviously before that, you will ensure that if the map does not contain that parent yet, you initialize its set of children with an empty set :

if (!map.containsKey(parent)) {
   map.put(parent, new HashSet());
}

In the end, you can iterate over the map, and display the size of each value set, for each key ...

HTH !

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM