Java List Intersect intersect2orderedList(List s1, List s2)

Here you can find the source of intersect2orderedList(List s1, List s2)

Description

Computes the intersection of 2 integer ordered lists.

License

Apache License

Parameter

Parameter Description
s1 shorter set
s2 longer set

Return

intersection result

Declaration

public static List<Integer> intersect2orderedList(List<Integer> s1, List<Integer> s2) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright [2014] [Joarder Kamal]//w ww  .  j  av a  2 s. c o  m
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 *******************************************************************************/

import java.util.*;

public class Main {
    /**
     * Computes the intersection of 2 integer ordered lists.
     * @param s1 shorter set 
     * @param s2 longer set
     * @return intersection result
     */
    public static List<Integer> intersect2orderedList(List<Integer> s1, List<Integer> s2) {

        if (s1.size() > s2.size())
            return intersect2orderedList(s2, s1);

        List<Integer> res = new ArrayList<Integer>();
        int pos1 = 0, pos2 = 0;

        while (pos1 < s1.size() && pos2 < s2.size()) {

            if (s1.get(pos1).equals(s2.get(pos2))) {
                res.add(s1.get(pos1));
                pos1++;
                pos2++;
            } else {
                if (s1.get(pos1) < s2.get(pos2))
                    pos1++;
                else
                    pos2++;
            }
        }

        return res;
    }
}

Related

  1. intersect(List lst1, List lst2)
  2. intersect(List list1, List list2)
  3. intersect(List... lists)
  4. intersect(List in1, List in2)
  5. intersect(Set a, List b)
  6. intersectAll(final List collector, final T[] a, final T[] b)
  7. intersectDate(List oDate, List tDate)
  8. intersection(final List list1, final List list2)
  9. intersection(final List list1, final List list2)