简体   繁体   English

Java按参数分割字符串数组

[英]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? 有没有办法使一个仅包含每种可能性的String数组一次?

 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. 顺便说一句,由于我正在为android编程,因此我无法使用Java 8的任何功能。

Sure: iterate the array and push the values into a Set. 当然:迭代数组并将值推入Set中。

When using the LinkedHashSet, you even keep the initial order. 使用LinkedHashSet时,甚至可以保持初始顺序。

Or, without looping manually: 或者,无需手动循环:

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

Simply copy the array into a Set : 只需将数组复制到Set

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

By definition, Set s do not contain duplicates. 根据定义, Set不包含重复项。 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. 您可以使用HashSet (或任何其他Set实现)而不是LinkedHashSet ,但是LinkedHashSet保留元素首次出现在数组中的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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