简体   繁体   中英

common elements between two collections in java

  public class Task1 {

     public static void main(String[] args) {

        List<Task> mainList = new ArrayList<>();
        Task e = new Task();
        e.setId(1);
        e.setName("shiva");
        mainList.add(e);

        e.setId(2);
        e.setName("Jyothi");
        mainList.add(e);

        e.setId(3);
        e.setName("Dinnu");
        mainList.add(e);

        //System.out.println(mainList);

        List<Task> subList = new ArrayList<>();

        Task e1 = new Task();
        e1.setId(1);
        e1.setName("shiva");
        subList.add(e1);


        List<Task> finalList = getFinalList(mainList, subList);
    }

...

    private static List<Task> getFinalList(List<Task> mainList, List<Task> subList) {
        List<Task> finalList = new ArrayList<>();

        System.out.println("final List: "+mainList.retainAll(subList));

        for(Task o : mainList){

            for(Task o1 : subList){

                if (o.equals(o1)){

                                  finalList.add(o);
                }
            }
        }

        System.out.println(finalList);
        return finalList;

But Still im unable to get the common elements..may i knw wat im making fault.

It's a fairly straightforward solution:

public static void main(String[] args) {
    List<String> list1 = new ArrayList<String>() {
        {
            add("string 1");
            add("string 2");
            add("string 3");
            add("string 4");
        }
    };
    List<String> list2 = new ArrayList<String>() {
        {
            add("string 4");
            add("string 5");
            add("string 3");
            add("string 6");
            add("string 3");
        }
    };

    Set<String> hash1 = new HashSet<>(list1);
    Set<String> hash2 = new HashSet<>(list2);

    hash1.retainAll(hash2);

    System.out.println(hash1);
}

This prints

[string 4, string 3]

Most of the code is setting up the values. Don't forget to implement .equals(Object o) and .hashCode() in your custom class.

You need to write an appropriate equals() method for the Task class. You created two different Task objects, and the default equals() implementation won't work in this case. Write a custom equals() that compares the id and name appropriately!

edit: Also, it looks like you aren't actually creating three Tasks for the first list. You create one new Task and then change its values. If you print out the size of the mainList after you are finished setting it up, it probably has the same Task object inside three times.

One possibility is to use Set data structures (where you don't allow duplications), you can find the union between two sets very easily. Google Guava for example provides that.

You modified same instance every time mainList has only one object

recreate it like this

    List<Task> mainList = new ArrayList<Task>();
    Task e = new Task();
    e.setId(1);
    e.setName("shiva");
    mainList.add(e);

    Task e1 = new Task();
    e1.setId(2);
    e1.setName("Jyothi");
    mainList.add(e1);

    Task e12 = new Task();
    e12.setId(3);
    e12.setName("Dinnu");
    mainList.add(e12);

    //System.out.println(mainList);

    List<Task> subList = new ArrayList<Task>();

    Task e13 = new Task();
    e13.setId(1);
    e13.setName("shiva");
    subList.add(e13);

and remove this line ...

      System.out.println("final List: "+mainList.retainAll(subList));

Use

      for(Task o : mainList){

        for(Task o1 : subList){

            if( ( o.getId() == o1.getId() ) && o.getName().equals(o1.getName()) ){
                                finalList.add(o);
      }     
        }
    }

    System.out.println(finalList);
    return finalList;

and implement hasCode() method in Task (If you using eclipse IDE means press alt+shift+s -> generate hash code and equals() it automatically generates)

I see one thing definitely wrong, and one thing potentially wrong here.

First, When you're done adding to your first list, the list contains three references to the same Task instance. Essentially, you have three Task references in the list that all have id=3 and name="dinnu". I'm guessing you probably intended to do this instead:

List<Task> mainList = new ArrayList<>();
Task e = new Task();
e.setId(1);
e.setName("shiva");
mainList.add(e);

e = new Task(); //Make a new instance
e.setId(2);
e.setName("Jyothi");
mainList.add(e);

e = new Task(); //Make a new instance
e.setId(3);
e.setName("Dinnu");
mainList.add(e);

Basically, since you forgot to make new instances, you were just changing the values on the same object instead of making new objects.

The second potential problem is that Java Collections will use the "equals()" method on your Task Object to determine object equality. If you don't have one, it will just check to see if the Objects refer to the same object instance, rather than comparing the object's properties. Therefore, you might need to implement an equals() method on your Task object as well if you don't already have one.

If you fix those things, than calling mainList.retainAll(subList) will remove all elements in mainList that are not present in subList. (finalList will not be necessary - that call will simply edit mainList)

If you would like to preserve mainList instead of editing it, then do this instead:

List<Task> finalList = new ArrayList<>(mainList); //Copy main into finalList
finalList.retainAll(subList); //remove elements that are not present in subList

One way to do it is by using hashtables instead of list . Since you have String and integer hasgtable will be ideal solution for your scenario and then you can use some thing like this to find the intersecting values from the two hashtables.

Hashtable<String, Integer> inersect = new Hashtable<String, Integer>(hashtable1);
inersect.keySet().retainAll(hashtable2.keySet());
System.out.println(inersect);

equals method for your custom object Task needs to be implemented by either making the Task class implement Comparable Class.

class Task implements Comparable<Task>{

@Override
public int compareTo(Task o) {
    return (o.getId()==this.getId() && o.getName().equals(this.getName());
}
//other class functions
}

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