Find the Intersect from the two list using Java 8

 Hi All,


Today I have released new video on "Find the Intersect from the two list using Java 8"


This is frequently asked question in Java Interview.


Please watch full video, share, like and Subscribe youtube channel and press bell icon. So you will get latest video notification.

 

Please click on below Image to view full explanation on below Youtube video .

Find the Intersect from the two list using Java 8


 package org.practice.basicprgms;


import java.util.ArrayList;

import java.util.Arrays;

import java.util.Collections;

import java.util.HashSet;

import java.util.List;

import java.util.Set;

import java.util.stream.Collectors;


public class FindIntersectionList {


public static void main(String[] args) {

List<Integer> list1 = Arrays.asList(1,2,3,4,5);

List<Integer> list2 = Arrays.asList(3,4,5,6,7);

List<Integer> intersectList = new ArrayList<>();

// 1. Using filter() and Contains method

intersectList =

list1.stream()

.filter(list2::contains)

.collect(Collectors.toList());

System.out.println("Using filter() and Contains method "+ intersectList);

// 2. Using Set

Set<Integer> intersectSet = new HashSet<>(list2);

intersectList =

list1.stream()

.filter(intersectSet::contains)

.collect(Collectors.toList());

System.out.println("Using Set "+ intersectList);

// 3. Using Collections.frequency()

intersectList =

list1.stream()

.filter(e -> Collections.frequency(list2, e) > 0)

.collect(Collectors.toList());

System.out.println("Using Collections.frequency() "+ intersectList);

// 4. Using flatMap

intersectList =

list1.stream()

.flatMap(e -> list2.stream().filter(e::equals))

.collect(Collectors.toList());

System.out.println("Using flatMap "+ intersectList);


// 5. Using Distinct() avoid duplicates

intersectList =

list1.stream()

.filter(list2::contains)

.distinct()

.collect(Collectors.toList());

System.out.println("Using Distinct() avoid duplicates "+ intersectList);


// 6. Using retainall traditional method

List<Integer> dupList = new ArrayList<>(list1);

dupList.retainAll(list2);

System.out.println("Using retainall traditional method "+ dupList);


// 7. Using Set Intersection

Set<Integer> set1 = new HashSet<>(list1);

Set<Integer> set2 = new HashSet<>(list2);

set1.retainAll(set2);

System.out.println("Using Set Intersection "+ set1);

// 8. Using foreach

for(int i : list1)

if(list2.contains(i) && !intersectList.contains(i))

intersectList.add(i);

System.out.println("Using foreach "+ intersectList);


}


}



Post a Comment

0 Comments