Computes the array of element indices which where added to a collection. - Java Collection Framework

Java examples for Collection Framework:Collections Utility Methods

Description

Computes the array of element indices which where added to a collection.

Demo Code

/*/*from   w  ww . ja v  a  2  s.  co m*/
 * Copyright (c) 2005-2016 Vincent Vandenschrick. All rights reserved.
 *
 *  This file is part of the Jspresso framework.
 *
 *  Jspresso is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  Jspresso 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 Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with Jspresso.  If not, see <http://www.gnu.org/licenses/>.
 */
//package com.java2s;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

public class Main {
    public static void main(String[] argv) {
        Collection smallCollection = java.util.Arrays.asList("asdf",
                "java2s.com");
        Collection bigCollection = java.util.Arrays.asList("asdf",
                "java2s.com");
        System.out.println(java.util.Arrays
                .toString(computeDifferenceIndices(smallCollection,
                        bigCollection)));
    }

    /**
     * Computes the array of element indices which where added to a collection.
     *
     * @param smallCollection
     *          the original collection.
     * @param bigCollection
     *          the collection with added elements.
     * @return the the array of element indices which where added to the original
     *         collection
     */
    public static int[] computeDifferenceIndices(
            Collection<?> smallCollection, Collection<?> bigCollection) {
        List<Integer> addedIndices = new ArrayList<>();
        int index = 0;
        for (Iterator<?> ite = bigCollection.iterator(); ite.hasNext(); index++) {
            if (smallCollection == null
                    || !smallCollection.contains(ite.next())) {
                if (smallCollection == null) {
                    ite.next();
                }
                addedIndices.add(index);
            }
        }
        int[] result = new int[addedIndices.size()];
        for (int i = 0; i < addedIndices.size(); i++) {
            result[i] = addedIndices.get(i);
        }
        return result;
    }
}

Related Tutorials