Here you can find the source of subtractSortedLists(List
Parameter | Description |
---|---|
a | a parameter |
b | Subtract two sorted lists returns (a-b); |
public static <T> List<T> subtractSortedLists(List<T> a, List<T> b, Comparator<T> comparator)
//package com.java2s; /*/* w w w . ja v a 2 s . c om*/ * ***** BEGIN LICENSE BLOCK ***** * Zimbra Collaboration Suite Server * Copyright (C) 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2016 Synacor, Inc. * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software Foundation, * version 2 of the License. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program. * If not, see <https://www.gnu.org/licenses/>. * ***** END LICENSE BLOCK ***** */ import java.util.ArrayList; import java.util.Comparator; import java.util.Iterator; import java.util.List; public class Main { /** * @param a * @param b * * Subtract two sorted lists * * returns (a-b); */ public static <T> List<T> subtractSortedLists(List<T> a, List<T> b, Comparator<T> comparator) { List<T> result = new ArrayList<T>(a.size()); Iterator<T> aIter = a.iterator(); Iterator<T> bIter = b.iterator(); T aVal = null; if (aIter.hasNext()) { aVal = aIter.next(); } T bVal = null; if (bIter.hasNext()) { bVal = bIter.next(); } while (aVal != null) { if (bVal == null) { result.add(aVal); } else { int comp = comparator.compare(aVal, bVal); if (comp < 0) { // a < b result.add(aVal); } else if (comp > 0) { // a > b if (bIter.hasNext()) { bVal = bIter.next(); } else { bVal = null; } continue; // DON'T move A fwd... } else { // a==b, so skip A! } } if (aIter.hasNext()) { aVal = aIter.next(); } else { aVal = null; } } return result; } }