Java Collection Unique getUniqueName(String name, Collection collection)

Here you can find the source of getUniqueName(String name, Collection collection)

Description

this gets a new, unique name given a string and an existing collection The name will be incremented by adding "x", where x is an integer, until a unique name is found

License

Open Source License

Parameter

Parameter Description
name the String to make unique
collection the existing collection to compare against

Return

the unique name

Declaration

public static String getUniqueName(String name, Collection collection) 

Method Source Code

//package com.java2s;
/*//  ww  w.j ava2  s.  c  o  m
 * JBoss, Home of Professional Open Source.
 *
 * See the LEGAL.txt file distributed with this work for information regarding copyright ownership and licensing.
 *
 * See the AUTHORS.txt file distributed with this work for a full listing of individual contributors.
 */

import java.util.Collection;
import java.util.Collections;

import java.util.Iterator;

public class Main {
    /**
     * this gets a new, unique name given a string and an existing collection The name will be incremented by adding "x", where x
     * is an integer, until a unique name is found
     * 
     * @param name the String to make unique
     * @param collection the existing collection to compare against
     * @return the unique name
     */
    public static String getUniqueName(String name, Collection collection) {
        if (collection == null) {
            collection = Collections.EMPTY_SET;
        }
        String result = name;
        int incr = 1;
        boolean nameIsInCollection = false;
        do {
            nameIsInCollection = false;
            // Perform a case-insensitive check against the collection
            for (Iterator i = collection.iterator(); i.hasNext();) {
                if (result.equalsIgnoreCase((String) i.next())) {
                    nameIsInCollection = true;
                    result = name + "_" + incr; //$NON-NLS-1$
                    incr++;
                    break;
                }
            }
        } while (nameIsInCollection);
        return result;
    }
}

Related

  1. addUnique(C collection, T item)
  2. addUnique(final Collection collection, final Object value)
  3. generateUniqueName(String aName, Collection aStringCollection)
  4. getUnique(Collection c)
  5. getUnique(Collection collection)
  6. getUniqueNameWithNumbers(Collection names, String baseName)
  7. getUniqueValue(Collection values, String initValue)
  8. hasUniqueObject(Collection collection)
  9. hasUniqueObject(Collection collection)