Java Program To Check List Having Common Values In List

Chapter: Interview Programs Last Updated: 17-05-2023 15:16:27 UTC

Program:

            /* ............... START ............... */
                import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class CommonValuesInList {
    public static void main(String[] args) {
        List<Integer> list1 = new ArrayList<>();
        list1.add(1);
        list1.add(2);
        list1.add(3);
        list1.add(4);
        
        List<Integer> list2 = new ArrayList<>();
        list2.add(3);
        list2.add(4);
        list2.add(5);
        list2.add(6);
        
        boolean hasCommonValues = hasCommonValues(list1, list2);
        
        if (hasCommonValues) {
            System.out.println("The lists have common values.");
        } else {
            System.out.println("The lists do not have common values.");
        }
    }
    
    public static boolean hasCommonValues(List<Integer> list1, List<Integer> list2) {
        Set<Integer> set1 = new HashSet<>(list1);
        
        for (Integer value : list2) {
            if (set1.contains(value)) {
                return true;
            }
        }
        
        return false;
    }
}

                /* ............... END ............... */
        

Output

The lists have common values.

In this case, list1 contains the values [1, 2, 3, 4] and list2 contains the values [3, 4, 5, 6]. 
As you can see, the lists have the common values 3 and 4. Therefore, the program outputs "The lists 
have common values."

Notes:

  • In this program, we have two lists (list1 and list2) containing integer values. The hasCommonValues method checks if there are any common values between the two lists. It does this by creating a HashSet from list1 to efficiently look up values. Then, it iterates over list2 and checks if each value is present in the HashSet. If a common value is found, it returns true. If no common values are found after checking all elements in list2, it returns false.
  • The program prints whether the lists have common values or not based on the result of the hasCommonValues method.

Tags

Java program to check list having common values in list # How to find common elements in two lists java # Find common elements in two lists in Java

Similar Programs Chapter Last Updated
Java Program To Convert Number Of Days Into Months And Days Interview Programs 14-06-2016
Java Program To Find Sum Of Integers Between 100 And 200 And Divisible By 7 Interview Programs 14-06-2016
Java Program To Find Minimum Of Two Numbers Using Conditional Operator Interview Programs 14-06-2016
Java Program To Print Calendar Of Month Interview Programs 13-06-2016

1