Java two lists intersection

Java Program For Finding Intersection Of Two Sorted Linked Lists

Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed.

Input: First linked list: 1->2->3->4->6 Second linked list be 2->4->6->8, Output: 2->4->6. The elements 2, 4, 6 are common in both the list so they appear in the intersection list. Input: First linked list: 1->2->3->4->5 Second linked list be 2->3->4, Output: 2->3->4 The elements 2, 3, 4 are common in both the list so they appear in the intersection list.

Method 1: Using Dummy Node.
Approach:
The idea is to use a temporary dummy node at the start of the result list. The pointer tail always points to the last node in the result list, so new nodes can be added easily. The dummy node initially gives the tail a memory space to point to. This dummy node is efficient, since it is only temporary, and it is allocated in the stack. The loop proceeds, removing one node from either ‘a’ or ‘b’ and adding it to the tail. When the given lists are traversed the result is in dummy. next, as the values are allocated from next node of the dummy. If both the elements are equal then remove both and insert the element to the tail. Else remove the smaller element among both the lists.

Below is the implementation of the above approach:

Источник

Пересечение двух списков в Java

В этом уроке мы узнаем, как получить пересечение двух List s .

Как и многое другое, это стало намного проще благодаря внедрению потоков в Java 8 .

2. Пересечение двух списков строк

Давайте создадим два List s из String с некоторым пересечением — оба содержат дублирующиеся элементы:

 ListString> list = Arrays.asList("red", "blue", "blue", "green", "red");   ListString> otherList = Arrays.asList("red", "green", "green", "yellow"); 

А теперь определим пересечение списков с помощью потоковых методов :

 SetString> result = list.stream()   .distinct()   .filter(otherList::contains)   .collect(Collectors.toSet());    SetString> commonElements = new HashSet(Arrays.asList("red", "green"));    Assert.assertEquals(commonElements, result); 

Во-первых, мы удаляем повторяющиеся элементы с разными . Затем мы используем фильтр для выбора элементов, которые также содержатся в otherList .

Наконец, мы преобразуем наш вывод с помощью Collector . Пересечение должно содержать каждый общий элемент только один раз. Порядок не должен иметь значения, поэтому toSet — самый простой выбор, но мы также можем использовать toList или другой метод сбора.

Дополнительные сведения см. в нашем руководстве по коллекторам Java 8 .

3. Пересечение списков пользовательских классов

Что, если наши List содержат не String , а экземпляры пользовательского класса, который мы создали? Ну, пока мы следуем соглашениям Java, решение с потоковыми методами будет прекрасно работать для нашего пользовательского класса.

Как метод contains решает, появляется ли конкретный объект в списке? На основе метода равных . Таким образом, мы должны переопределить метод equals и убедиться, что он сравнивает два объекта на основе значений соответствующих свойств.

Например, два прямоугольника равны, если их ширина и высота равны.

Если мы не переопределяем метод equals , наш класс использует реализацию equals родительского класса. В конце дня, вернее, в цепочке наследования выполняется метод equals класса Object . Тогда два экземпляра равны, только если они ссылаются на один и тот же объект в куче. «

Для получения дополнительной информации о методе equals см. нашу статью о контрактах Java equals() и hashCode() .

4. Вывод

В этой быстрой статье мы увидели, как использовать потоки для вычисления пересечения двух списков. Есть много других операций, которые раньше были довольно утомительными, но довольно простыми, если мы знаем, как работать с Java Stream API. Взгляните на наши дальнейшие руководства с потоками Java здесь .

Источник

Java 8 : Find union and intersection of two Lists (ArrayLists)

sneppets-java8

This tutorial shows you how to find union and intersection of two Lists (ArrayLists).

Union and Intersection of two Lists

package com.sneppets.example; 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 UnionIntersectionOfTwoListsExample < public static void main (String[] args) < Listlist1 = new ArrayList(Arrays.asList("a","b","c","d","e")); System.out.println("List 1 elements: " + list1); List list2 = new ArrayList(Arrays.asList("b","d","f","g")); System.out.println("List 2 elements: " + list2); System.out.println(); System.out.println("Union. "); //Find union of two lists System.out.println("Union of List1 and List2 :" + getUnionOfLists(list1, list2)); System.out.println(); System.out.println("Intersection. "); //Find intersect of lists using Stream API (Java 8) System.out.println("Intersection of List1 & List2 Method 1: " + getIntersectOfLists1(list1, list2)); //Find intersect of lists using retainAll() method System.out.println("Intersection of List1 & List2 Method 2: " + getIntersectOfLists2(list1, list2)); > private static List getUnionOfLists(List list1, List list2) < Setset = new HashSet<>(); set.addAll(list1); set.addAll(list2); return new ArrayList<>(set); > private static List getIntersectOfLists1(List list1, List list2) < ListintersectElements = list1.stream() .filter(list2 :: contains) .collect(Collectors.toList()); if(!intersectElements.isEmpty()) < return intersectElements; >else < return Collections.emptyList(); >> private static List getIntersectOfLists2(List list1, List list2) < list1.retainAll(list2); return list1; >>
List 1 elements: [a, b, c, d, e] List 2 elements: [b, d, f, g] Union. Union of List1 and List2 :[a, b, c, d, e, f, g] Intersection. Intersection of List1 & List2 Method 1: [b, d] Intersection of List1 & List2 Method 2: [b, d]

Union of two Lists

To find union of two lists you need to use addAll() method of Set interface and ArrayList constructor. You need to create new Set and add elements from list1 and list2 and construct new ArrayList using that set as shown.

private static List getUnionOfLists(List list1, List list2) < Setset = new HashSet<>(); set.addAll(list1); set.addAll(list2); return new ArrayList<>(set); >

Intersection of two Lists

1. Java 8 Stream API

List intersectElements = list1.stream() .filter(list2 :: contains) .collect(Collectors.toList());

From Java 8 you can use sequential stream on list1 (bigger one) and filter it to produce a stream containing matching elements of specified collection (list2) and use Collectors.toList() to accumulate the intersects in to new List.

2. retainAll() method

The above code removes the elements from List1 that are not contained in the specified collection (List2).

Also See

References

Источник

Java Program For Union And Intersection Of Two Linked Lists

Given two Linked Lists, create union and intersection lists that contain union and intersection of the elements present in the given lists. The order of elements in output lists doesn’t matter.
Example:

Input: List1: 10->15->4->20 List2: 8->4->2->10 Output: Intersection List: 4->10 Union List: 2->8->20->4->15->10

Method 1 (Simple):
The following are simple algorithms to get union and intersection lists respectively.
1. Intersection (list1, list2):
Initialize the result list as NULL. Traverse list1 and look for every element in list2, if the element is present in list2, then add the element to the result.
2. Union (list1, list2):
Initialize the result list as NULL. Traverse list1 and add all of its elements to the result.
Traverse list2. If an element of list2 is already present in the result then do not insert it to the result, otherwise insert.
This method assumes that there are no duplicates in the given lists.
Thanks to Shekhu for suggesting this method. Following are C and Java implementations of this method.

Java

First list is 10 15 4 20 Second list is 8 4 2 10 Intersection list is 4 10 Union list is 2 8 20 4 15 10

Complexity Analysis:

  • Time Complexity: O(m*n).
    Here ‘m’ and ‘n’ are number of elements present in the first and second lists respectively.
    For union: For every element in list-2 we check if that element is already present in the resultant list made using list-1.
    For intersection: For every element in list-1 we check if that element is also present in list-2.
  • Auxiliary Space: O(1).
    No use of any data structure for storing values.

Method 2 (Use Merge Sort):
In this method, algorithms for Union and Intersection are very similar. First, we sort the given lists, then we traverse the sorted lists to get union and intersection.
The following are the steps to be followed to get union and intersection lists.

  1. Sort the first Linked List using merge sort. This step takes O(mLogm) time. Refer this post for details of this step.
  2. Sort the second Linked List using merge sort. This step takes O(nLogn) time. Refer this post for details of this step.
  3. Linearly scan both sorted lists to get the union and intersection. This step takes O(m + n) time. This step can be implemented using the same algorithm as sorted arrays algorithm discussed here.

The time complexity of this method is O(mLogm + nLogn) which is better than method 1’s time complexity.
Method 3 (Use Hashing):
1. Union (list1, list2):
Initialize the result list as NULL and create an empty hash table. Traverse both lists one by one, for each element being visited, look at the element in the hash table. If the element is not present, then insert the element into the result list. If the element is present, then ignore it.
2. Intersection (list1, list2)
Initialize the result list as NULL and create an empty hash table. Traverse list1. For each element being visited in list1, insert the element in the hash table. Traverse list2, for each element being visited in list2, look the element in the hash table. If the element is present, then insert the element to the result list. If the element is not present, then ignore it.
Both of the above methods assume that there are no duplicates.

Источник

Intersection of two linked lists

If you want to practice data structure and algorithm programs, you can go through 100+ java coding interview questions.

In this post, we will see how to find Intersection of two linked lists.

Problem

Given two singly linked lists, find if two linked lists intersect. If they intersect, find intersection point.

Solution

Here is simple algorithm to find Intersection of two linked lists.

  • Find the length of both singly linked lists.
  • Find the bigger linked list and iterate up to the difference between two linked list.
  • Please note that two linked list will become equal at this step.
  • Iterate over both linked list and check if there is any common node, if you find one, return it.
  • Else return null.

When you run above program, you will get below output

That;s all about finding Intersection of two linked lists.

Was this post helpful?

You may also like:

Convert Postfix to Infix in Java

Convert Prefix to Postfix in Java

Infix to Postfix Conversion in Java

Queue implementation in java

Implement Queue using Linked List in java

Convert sorted Linked List to balanced BST

Sort a Stack using another stack

Find length of Linked List in java

Implement singly linked list in java

Stack implementation in java

Share this

Author

Implement Queue using Linked List in java

If you want to practice data structure and algorithm programs, you can go through 100+ java coding interview questions. In this post , we will see how to implement Queue using Linked List in java. Queue is abstract data type which demonstrates First in first out (FIFO) behaviour. We will implement same behaviour using Array. Although java provides implementation […]

Convert sorted Linked List to balanced BST

Table of ContentsSolution 1:Solution 2:Java Program to convert sorted LinkedList to balanced BST: If you want to practice data structure and algorithm programs, you can go through 100+ java coding interview questions. In this post , we will see how to convert sorted LinkedList to balanced binary search tree. There are two ways to do it. […]

Find length of Linked List in java

Table of ContentsIterative:Recursion:Java program to find length of LinkedList: If you want to practice data structure and algorithm programs, you can go through data structure and algorithm programs. In this post, we will see how to find length of Linked List in java. You can obviously use size() method of java Linked List class but here […]

Implement singly linked list in java

Table of ContentsAn example of linked list:Let’s implement Linked List in java. In this post, we will see how to implement singly linked list in java. It is one of the most used data structure. In singly linked list, Node has data and pointer to next node. It does not have pointer to the previous […]

Implement stack using Linked List in java

If you want to practice data structure and algorithm programs, you can go through 100+ java coding interview questions. In this program, we will see how to implement stack using Linked List in java. The Stack is an abstract data type that demonstrates Last in first out (LIFO) behavior. We will implement the same behavior using […]

How to check if linked list is palindrome in java

Table of ContentsJava Linked List Interview Programs:Algorithm:Java Program: In this post, we will see how to check if linked list is palindrome or not. Java Linked List Interview Programs: How to reverse a linked list in java How to reverse a linked list in pairs in java How to find middle element of linked list […]

Источник

Читайте также:  Javascript удалить часть страницы
Оцените статью