Java Collection Unique hasUniqueObject(Collection collection)

Here you can find the source of hasUniqueObject(Collection collection)

Description

CollectionUtils Determine whether the given Collection only contains a single unique object.

License

Apache License

Parameter

Parameter Description
collection the Collection to check

Return

true if the collection contains a single reference or multiple references to the same instance, false else

Declaration

@SuppressWarnings("rawtypes")
public static boolean hasUniqueObject(Collection collection) 

Method Source Code

//package com.java2s;
/*//from   w  w  w.ja v a2s  . c  o  m
 * @(#)SpringUtils.java
 * Create by Zollty_Tsow on 2013-11-30 
 * you may find ZollTy at csdn, github, oschina, stackoverflow...
 * e.g. https://github.com/zollty  http://www.cnblogs.com/zollty 
 * 
 * Copyright 2012-2013 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *      http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * 
 */

import java.util.Collection;

public class Main {
    /** CollectionUtils
     * Determine whether the given Collection only contains a single unique object.
     * @param collection the Collection to check
     * @return {@code true} if the collection contains a single reference or
     * multiple references to the same instance, {@code false} else
     */
    @SuppressWarnings("rawtypes")
    public static boolean hasUniqueObject(Collection collection) {
        if (collection == null || collection.isEmpty()) {
            return false;
        }
        boolean hasCandidate = false;
        Object candidate = null;
        for (Object elem : collection) {
            if (!hasCandidate) {
                hasCandidate = true;
                candidate = elem;
            } else if (candidate != elem) {
                return false;
            }
        }
        return true;
    }

    /**
     * Determine whether the given array is empty:
     * i.e. {@code null} or of zero length.
     * @param array the array to check
     */
    public static boolean isEmpty(Object[] array) {
        return (array == null || array.length == 0);
    }
}

Related

  1. getUnique(Collection collection)
  2. getUniqueName(String name, Collection collection)
  3. getUniqueNameWithNumbers(Collection names, String baseName)
  4. getUniqueValue(Collection values, String initValue)
  5. hasUniqueObject(Collection collection)
  6. hasUniqueObject(Collection collection)
  7. unique(Collection c)
  8. unique(Collection c, Collection result)
  9. uniqueIdNotIn(String prefix, Collection exclusions)