I am working with Java 8.
I need, having an array of strings whose content I do not know and in which there may or may not be repetitions, to obtain that content, without repetitions and without altering the original order. For example, if I had:
String[] strs = {"orange", "apple", "apple", "banana", "grape", "apple", "lemon"};
Should get:
{"orange", "apple", "banana", "grape", "lemon"};
I currently use the following method to filter repeats, but it tends to mess things up:
/**
* Filters repeated strings in the array
*
* @param arrStr
* @return
*/
public static String[] filterRepeatedStr(String[] arrStr) {
List<String> arr = Arrays.asList(arrStr);
Set<String> hs = new HashSet();
hs.addAll(arr);
return hs.toArray(new String[hs.size()]);
}
The problem is the use of
HashSet
, the option is the use ofLinkedHashSet
, since itLinkedHashSet
stores elements based on insertion order:As a result you would get:
Something important to comment on is that using
HashSet
it has better performance but it does not guarantee any order in the elements, on the other handLinkedHashSet
it does, but performance is sacrificed.By using Stream it is made simple.
I update. So you could work with functional interfaces . I'm going to give an example with the UnaryOperator interface , which receives a type and returns a value of the same type.
Ex:
With Streams you can remove repeated values and have an array again without creating other collections. In addition, the Arrays library greatly facilitates the work of manipulating arrays.