Java Array Remove removeElement(String array[], String element, int occurrences)

Here you can find the source of removeElement(String array[], String element, int occurrences)

Description

Remove an element from array.

License

Open Source License

Parameter

Parameter Description
array a parameter
element a parameter
occurrences 0 for all or the maximum number of occurences to remove.

Declaration

public static String[] removeElement(String array[], String element, int occurrences) 

Method Source Code


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

import java.util.ArrayList;
import java.util.List;

public class Main {
    /**// ww  w.  j  av  a  2  s. c om
     * Remove an element from array.
     * 
     * @param array
     * @param element
     * @param occurrences
     *            0 for all or the maximum number of occurences to remove.
     * @return
     */
    public static String[] removeElement(String array[], String element, int occurrences) {

        List<String> list = new ArrayList<String>();

        if (array.length == 1) {
            return new String[0];
        }

        int removed = 0;

        for (String s : array) {
            if (s.trim().toUpperCase().equals(element.trim().toUpperCase())) {
                removed++;

                if (removed <= occurrences) {
                    continue;
                }
            }

            list.add(s);
        }

        String newArray[] = new String[list.size()];

        for (int i = 0; i < list.size(); i++) {
            newArray[i] = list.get(i);
        }

        return newArray;
    }
}

Related

  1. removeByPrefix(String[] array, String prefix)
  2. removeByteOrderMark(final byte[] input)
  3. removeCommonWords(String[] words)
  4. removeElement(final E[] array, final int index)
  5. removeElement(Object[] array, Object entryToRemove)
  6. removeElement(String[] array, String remove)
  7. removeElement(String[] elements, String element)
  8. removeElement(T[] array, int i)
  9. removeElement(T[] array, T removeObject)