简体   繁体   中英

Java split string array by parameter

Let's say we have a string array like this:

{abc,abc,abc,def,def,ghi}

Is there a way to make a String array containing each possibility only once?

 e.g. {abc,def,ghi}

I was thinking about iterating over an array, sorted beforehand, and checking if the previous elements equals the next one. If not add it to list and convert it to array later on if necessary.

But is there a simpler solution ?

By the way, since I am programming for android, I can't use any features of Java 8.

Sure: iterate the array and push the values into a Set.

When using the LinkedHashSet, you even keep the initial order.

Or, without looping manually:

Set<String> = new LinkedHashSet<>(Arrays.asList(yourArray)) ;

Simply copy the array into a Set :

Set<String> noDupes = new LinkedHashSet<>(Arrays.asList(yourArray));

By definition, Set s do not contain duplicates. You can use HashSet (or any other Set implementation) rather than LinkedHashSet , but LinkedHashSet preserves the order in which the elements first appear in the array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM