Java Collection Unique generateUniqueName(String aName, Collection aStringCollection)

Here you can find the source of generateUniqueName(String aName, Collection aStringCollection)

Description

Generates a unique name for the child.

License

Open Source License

Parameter

Parameter Description
aName a parameter
aStringCollection a parameter

Declaration

public static String generateUniqueName(String aName,
        Collection<String> aStringCollection) 

Method Source Code

//package com.java2s;

import java.util.*;

public class Main {
    /**// w ww .  ja v  a 2 s  .c  o m
     * Generates a unique name for the child.
     *
     * @param aName
     * @param aStringCollection
     */
    public static String generateUniqueName(String aName,
            Collection<String> aStringCollection) {
        return generateUniqueName(aName, aStringCollection, false);
    }

    /**
     * Generates a unique name for the child.
     *
     * @param aPrefix
     * @param aStringCollection
     * @param aPreserveIfAlreadyUnique
     */
    public static String generateUniqueName(String aPrefix,
            Collection<String> aStringCollection,
            boolean aPreserveIfAlreadyUnique) {
        Set<String> set = new HashSet<>();
        set.addAll(aStringCollection);

        if (aPreserveIfAlreadyUnique && !set.contains(aPrefix))
            return aPrefix;

        int counter = 1;
        while (set.contains(aPrefix + String.valueOf(counter)))
            counter++;

        return aPrefix + counter;
    }
}

Related

  1. addUnique(C collection, T item)
  2. addUnique(final Collection collection, final Object value)
  3. getUnique(Collection c)
  4. getUnique(Collection collection)
  5. getUniqueName(String name, Collection collection)
  6. getUniqueNameWithNumbers(Collection names, String baseName)