0

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!

1
  • Is ID is unique to identify an article? Commented Mar 14, 2016 at 3:29

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

-1

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.

2 Comments

This should be a comment rather than an answer!
Android doesn't have Java 8 support. Look at the tags. It's an Android question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.