Java examples for java.lang:String Array
Remove duplicate Strings from the given array.
//package com.java2s; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.Set; import java.util.TreeSet; public class Main { public static void main(String[] argv) throws Exception { String[] array = new String[] { "1", "abc", "level", null, "java2s.com", "asdf 123" }; System.out.println(java.util.Arrays .toString(removeDuplicateStrings(array))); }/* www. j a va 2 s. c o m*/ /** * Remove duplicate Strings from the given array. Also sorts the array, as it uses a TreeSet. * * @param array * the String array * @return an array without duplicates, in natural sort order */ public static String[] removeDuplicateStrings(final String[] array) { // if (ObjectUtils.isEmpty(array)) { if (array.length == 0) return array; final Set<String> set = new TreeSet<String>(); for (final String element : array) { set.add(element); } return toStringArray(set); } /** * Copy the given Collection into a String array. The Collection must contain String elements only. * * @param collection * the Collection to copy * @return the String array (<code>null</code> if the passed-in Collection was <code>null</code>) */ public static String[] toStringArray(final Collection<String> collection) { if (collection == null) return null; return collection.toArray(new String[collection.size()]); } /** * Copy the given Enumeration into a String array. The Enumeration must contain String elements only. * * @param enumeration * the Enumeration to copy * @return the String array (<code>null</code> if the passed-in Enumeration was <code>null</code>) */ public static String[] toStringArray( final Enumeration<String> enumeration) { if (enumeration == null) return null; final List<String> list = Collections.list(enumeration); return list.toArray(new String[list.size()]); } }