Java 8 compare two lists of objects and get common elements

Example:

Input: a = {"1","2","3","4","5"} b = {"1","2","3"} Result: 1,2,3

Get Common Elements from two Lists:

retainAll() method from the Collection interface is used to remove the common elements from two different lists.

Find common elements in two ArrayLists in Java


Prerequisite: ArrayList in Java

Given two ArrayLists, the task is to print all common elements in both the ArrayLists in Java .

Examples:

Input: List1 = ["Hii", "Geeks", "for", "Geeks"], List2 = ["Hii", "Geeks", "Gaurav"] Output: [Hii, Geeks, Geeks] Input: List1 = ["a", "b", "c", "d", "e", "f"], List2 = ["b", "d", "e", "h", "g", "c"] Output:[b, c, d, e]
  1. Using Collections.retainAll() method

    Syntax:

    Collections1.retainAll(Collections2) This method keeps only the common elements of both Collection in Collection1.

    Approach:



    1. Get the two ArrayLists.
    2. Find the common elements in both the Lists using Collection.retainAll() method. This method keeps only the common elements of both Collection in Collection1.
    3. The List 1 now contains the common elements only.

    Below is the implementation of the above approach:
    Program: By modifying the contents of List1.




    // Java Program to find common elements

    // in two ArrayLists

    // Using retainAll() method

    // import ArrayList package

    import java.util.ArrayList;

    public class GFG {

    // main method

    public static void main(String[] args)

    {

    // create ArrayList list1

    ArrayList<String>

    list1 = new ArrayList<String>();

    // Add values in ArrayList

    list1.add("Hii");

    list1.add("Geeks");

    list1.add("for");

    list1.add("Geeks");

    // print list 1

    System.out.println("List1: "

    + list1);

    // Create ArrayList list2

    ArrayList<String>

    list2 = new ArrayList<String>();

    // Add values in ArrayList

    list2.add("Hii");

    list2.add("Geeks");

    list2.add("Gaurav");

    // print list 2

    System.out.println("List2: "

    + list2);

    // Find the common elements

    list1.retainAll(list2);

    // print list 1

    System.out.println("Common elements: "

    + list1);

    }

    }

    Output: List1: [Hii, Geeks, for, Geeks] List2: [Hii, Geeks, Gaurav] Common elements: [Hii, Geeks, Geeks]

    Program 2: By retaining the contents of List1.




    // Java Program to find common elements

    // in two ArrayLists

    // Using retainAll() method

    // import ArrayList package

    import java.util.ArrayList;

    public class GFG {

    // main method

    public static void main(String[] args)

    {

    // create ArrayList list1

    ArrayList<String>

    list1 = new ArrayList<String>();

    // Add values in ArrayList

    list1.add("Hii");

    list1.add("Geeks");

    list1.add("for");

    list1.add("Geeks");

    // print list 1

    System.out.println("List1: "

    + list1);

    // Create ArrayList list2

    ArrayList<String>

    list2 = new ArrayList<String>();

    // Add values in ArrayList

    list2.add("Hii");

    list2.add("Geeks");

    list2.add("Gaurav");

    // print list 2

    System.out.println("List2: "

    + list2);

    // Create ArrayList list3

    ArrayList<String>

    list3 = new ArrayList<String>(list1);

    // Store the comparison output

    // in ArrayList list3

    list3.retainAll(list2);

    // print list 3

    System.out.println("Common elements: "

    + list3);

    }

    }

    Output: List1: [Hii, Geeks, for, Geeks] List2: [Hii, Geeks, Gaurav] Common elements: [Hii, Geeks, Geeks]

  2. Using Stream filter

    Syntax:

    list1.stream() .filter(list2::contains) .collect(Collectors .toList())); This method returns element if found in second list.

    Approach:

    1. First create two ArrayList and add values of list.
    2. Convert the ArrayList to Stream using stream() method.
    3. Set the filter condition to be distinct using contains() method.
    4. Collect the filtered values as List using collect() method. This list will be return common element in both list.
    5. Print list3

    Below is the implementation of the above approach:

    Program:




    // Java Program to find common elements

    // in two ArrayLists

    // Using Stream filter method

    // import ArrayList package

    import java.util.*;

    import java.util.stream.*;

    public class GFG {

    // main method

    public static void main(String[] args)

    {

    // create ArrayList list1

    ArrayList<String>

    list1 = new ArrayList<String>();

    // Add values in ArrayList

    list1.add("Hii");

    list1.add("Geeks");

    list1.add("for");

    list1.add("Geeks");

    // print list 1

    System.out.println("List1: "

    + list1);

    // Create ArrayList list2

    ArrayList<String>

    list2 = new ArrayList<String>();

    // Add values in ArrayList

    list2.add("Hii");

    list2.add("Geeks");

    list2.add("Gaurav");

    // print list 2

    System.out.println("List2: "

    + list2);

    // Find common elements

    System.out.print("Common elements: ");

    System.out.println(list1.stream()

    .filter(list2::contains)

    .collect(Collectors

    .toList()));

    }

    }

    Output: List1: [Hii, Geeks, for, Geeks] List2: [Hii, Geeks, Gaurav] Common elements: [Hii, Geeks, Geeks]

  3. Naive approach:
    1. First create two ArrayList and add values of list.
    2. Create a temporary ArrayList to contain common elements.
    3. Iterate through the list1 and check if that element is present in the list2 using ArrayList.contains() method.
    4. If found, add it to the list3
    5. Print the common elements from list3

    Below is the implementation of the above approach:




    // Java Program to find common elements

    // in two ArrayLists

    // Using Stream filter method

    // import ArrayList package

    import java.util.ArrayList;

    public class GFG {

    // main method

    public static void main(String[] args)

    {

    // create ArrayList list1

    ArrayList<String>

    list1 = new ArrayList<String>();

    // Add values in ArrayList

    list1.add("Hii");

    list1.add("Geeks");

    list1.add("for");

    list1.add("Geeks");

    // print list 1

    System.out.println("List1: "

    + list1);

    // Create ArrayList list2

    ArrayList<String>

    list2 = new ArrayList<String>();

    // Add values in ArrayList

    list2.add("Hii");

    list2.add("Geeks");

    list2.add("Gaurav");

    // print list 2

    System.out.println("List2: "

    + list2);

    // Create ArrayList list3

    ArrayList<String>

    list3 = new ArrayList<String>();

    // Find common elements

    // while iterating through list1

    for (String temp : list1) {

    // Check if theis element is

    // present in list2 or not

    if (list2.contains(temp)) {

    // Since present, add it to list3

    list3.add(temp);

    }

    }

    // print common elements from list 3

    System.out.println("Common elements: "

    + list3);

    }

    }

    Output: List1: [Hii, Geeks, for, Geeks] List2: [Hii, Geeks, Gaurav] Common elements: [Hii, Geeks, Geeks]




Article Tags :

Java

Technical Scripter

Java - util package

Java-Collections

Java-List-Programs

Technical Scripter 2018

Practice Tags :

Java

Java-Collections

Read Full Article

1. Overview

In this tutorial, we'll learn how to retrieve the intersection of two Lists.

Like many other things,this has become much easier thanks to the introduction ofstreams in Java 8.

1. Overview

Finding differences between collections of objects of the same data type is a common programming task. As an example, imagine we have a list of students who applied for an exam and another list of students who passed it. The difference between those two lists would give us the students who didn't pass the exam.

In Java, there's no explicit way for finding differences between two lists in the List API, though there are some helper methods that come close.

In this quick tutorial, we'll look at how to find the differences between the two lists. We'll try a few different approaches, including plain Java (with and without Streams) and using third-party libraries such as Guava and the Apache Commons Collections.

How to Compare List Objects in Java 7 vs. Java 8

In this blast from the not-too-distant past, we compare how Java 8's Stream API changed how you can compare List objects.

by

Arpan Das

·

Jun. 01, 18 · Java Zone · Tutorial

Like (12)

Comment

Save

Tweet

259.66K Views

Join the DZone community and get the full member experience.

Join For Free

Comparing the content of Lists against some condition is a common use case to handle in many business scenarios. This comparison can be broadly classified as:

  1. Comparing each element of a List against some condition. As an example, you have a List of Employee Objects and you need to check that all your Employees are above 18.
  2. One or more elements from one List match(es) the elements of another List.
  3. All elements of a List exist in another List.

Now, developing these use cases is very easy in Java 7 with relatively few lines of code. The following is an example where we are comparing two Lists in Java 7 and checking if any element from List 1 exists in List 2.

package com.tuturself; import java.util.Arrays; import java.util.List; public class ListCompare { public static void main(String[] args) { List < Integer > aList = Arrays.asList(new Integer[] { 1, 3, 5, 6, 8 }); List < Integer > bList = Arrays.asList(new Integer[] { 10, 89, 8, 9 }); for (Integer i: aList) { if (bList.contains(i)) { System.out.println("Match Found " + i); break; } } } }


Now let us develop all the above use cases in Java 8. The Java 8 Stream API provides threemethods allMatch, anyMatch, and noneMatch, which can be applied to a stream object that matches the given Predicate and then returns a boolean value. It is recommended to check the following articles if you are not familiar with the Stream API.

  • Example of different kinds of streams in Java 8.

  • Example of different kinds of streams in Java 8 [Part 2]

1. Compare two arraylists for equality

Java program to test if two given lists are equal. To test equality –

  • Sort both lists.
  • Compare both lists using equals() method.

List.equals() method return true if both elements are of same size and both contains same set of elements in exactly same order.

public class ArrayListExample { public static void main(String[] args) { ArrayList<String> listOne = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "f")); ArrayList<String> listTwo = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e")); Collections.sort(listOne); Collections.sort(listTwo); //Compare unequal lists example boolean isEqual = listOne.equals(listTwo); //false System.out.println(isEqual); //Compare equals lists example ArrayList<String> listThree = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "f")); isEqual = listOne.equals(listThree); //true System.out.println(isEqual); } }

Program output.

false true

1. Introduction


In this article, We'll learn how to compare two ArrayLists for checking Objects equality.



ArrayList has an equal() method that takes one argument type of Object. This equals() method compares the passed list object with the current list object. If both lists are having same values then it returns true, otherwise false. equals()

Read more on how to compare two strings lexicographically.

Example programs are shown on equals(), containsAll() and java 8 Stream API.


At the end of the article you will be good with comparing two lists and find differences between two lists in java







Video liên quan

Postingan terbaru

LIHAT SEMUA