Java Array Unique getUniqueItems(final String[] allItems, final String newItem, final int maxItems)

Here you can find the source of getUniqueItems(final String[] allItems, final String newItem, final int maxItems)

Description

Remove duplicate items from a list and add a new item.

License

Open Source License

Parameter

Parameter Description
allItems a parameter
newItem a parameter
maxItems a parameter

Declaration

public static String[] getUniqueItems(final String[] allItems, final String newItem, final int maxItems) 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (C) 2005, 2016 Wolfgang Schramm and Contributors
 *
 * 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./*from  w w  w.j av a 2s  .  com*/
 *
 * 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, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
 *******************************************************************************/

import java.util.ArrayList;

public class Main {
    /**
     * Remove duplicate items from a list and add a new item.
     * 
     * @param allItems
     * @param newItem
     * @param maxItems
     * @return
     */
    public static String[] getUniqueItems(final String[] allItems, final String newItem, final int maxItems) {

        if (newItem == null) {

            // there is no new item
            return allItems;
        }

        final ArrayList<String> newItems = new ArrayList<String>();

        newItems.add(newItem);

        for (final String oldItem : allItems) {

            // ignore duplicate entries
            if (newItem.equals(oldItem) == false) {
                newItems.add(oldItem);
            }

            if (maxItems > 0) {
                if (newItems.size() >= maxItems) {
                    break;
                }
            }
        }

        return newItems.toArray(new String[newItems.size()]);
    }
}

Related

  1. countUnique(int[][] array)
  2. getUniqueIDsArray(int[] idArray, String ids, String seperator)
  3. getUniqueWords(String[] input)
  4. invertRelabeling(int[] relabeling, int[] uniqueVars, int maxVarNum)
  5. unique(double[] in)
  6. unique(int[] a, int aLen, int[] b, int bLen)