简体   繁体   中英

How to get different values from two ArrayList in Java/Android?

I have two List

Class Article

public class Article{
 int id;
 String name;

// get
// set

}

List one:

List<Article> mListInfor have

id =  1, 2 , 3, 4, 5
name = "A", "B", "C", "D", "E"

List Two:

List<Article> mListNews have

id =   1, 2, 3, 4, 5, 6, 7, 8

name = "A", "B", "C", "D", "E", "F", "G", "H"

Result:

List<Article> mListDiffrent have

id = 6,7,8

name = "F","G","H"

How can I get different value from these two arraylists: List mListInfor and List mListNews ?

Please. Help me!

You should override the Equals method in your class, and then use some built-in methods. For example

public class Article{
    int id;
    String name;

    // get
    // set
    @Override
    public boolean equals(Object obj) {
       if (!(obj instanceof Article))
          return false;
       if (obj == this)
          return true;
       return this.id == obj.id;
    }
} 

List<Article> differences = new ArrayList<>();
differences.addAll(mListInfor)
differences.removeAll(mListNews)

Edit

Depending on the order of your call to removeAll, the result can be affected. However, there is a already-built feature in apache commons ( CollectionUtils ) which will make you not worry about that.

CollectionUtils.intersection(mListInfor, mListNews);

Solution given by @rafael in above answer is good solution where you are using inbuilt feature.

You can also create a function where you can individually traverse each element of article lost and segregate by using comparator implementation or even equals comparison is good.

Also don't forget to explore streams in Java 8. There must be good options in stream api.

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