Java List Intersect intersectSortedAscending(List l1, List l2)

Here you can find the source of intersectSortedAscending(List l1, List l2)

Description

Checks for intersection of lists, exploiting that the lists are (must be!) sorted in ascending order of the hashcodes of their elements.

License

Open Source License

Declaration

private static boolean intersectSortedAscending(List<? extends Object> l1, List<? extends Object> l2) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.Iterator;

import java.util.List;

public class Main {
    /** Checks for intersection of lists, exploiting that the lists are (must be!) sorted in ascending order of the hashcodes of their elements. */
    private static boolean intersectSortedAscending(List<? extends Object> l1, List<? extends Object> l2) {
        // use iterators
        Iterator<? extends Object> it1 = l1.iterator();
        Iterator<? extends Object> it2 = l2.iterator();
        if (!it1.hasNext() || !it2.hasNext())
            return false; // one of the list is empty; no possible intersection
        // start iterating over l1 or l2, based on lowest hash code
        Object o1 = it1.next();/* w  w w .j  a va2 s. c o m*/
        Object o2 = it2.next();
        int h1 = o1.hashCode();
        int h2 = o2.hashCode();
        while (true) {
            // compare objects only if hash code is the same
            if (h1 == h2 && o1.equals(o2))
                return true;

            // objects are different; determine whether to advance o1 or o2 to next element
            if (h1 <= h2) {
                if (it1.hasNext()) {
                    o1 = it1.next();
                    h1 = o1.hashCode();
                } else
                    return false;
            } else {
                if (it2.hasNext()) {
                    o2 = it2.next();
                    h2 = o2.hashCode();
                } else
                    return false;
            }
        }
    }
}

Related

  1. intersection(List listOne, List listTwo)
  2. intersection(List set1, List set2)
  3. intersection_type(List list1, List list2)
  4. intersectionInplace(List> sets)
  5. intersectList(List list1, List list2)
  6. isListIntersect(List list1, List list2)
  7. removeIntersection(List intervals, List intervalsToRemove)