Given a filtered string. I want to add its substrings to an ArrayList
only if it doesn't contain it already.
My code:
Pattern reg = Pattern.compile(",");
ArrayList<String> SANR = reg.splitAsStream(joiner.toString())
.filter(role -> role.contains("ABB"))
.map(str -> str.replaceAll("ABB", ""))
.collect(Collectors.toCollection(ArrayList::new));
As input, it gets all the values with ABB
appended such as [123,123,244,244,255]
, so I want to make sure the output is just:
[123,244,255]
CodePudding user response:
You need to apply distict()
operation to ensure that the result doesn't contain duplicates. To achieve it and preserve the initial order of elements in the stream, it uses LinkedHashSet
under the hood.
Don't use ArrayList
as a type, it makes your code rigid. See What does it mean to "program to an interface"?
By the way, Collectors.toList()
as well as Java 16 toList()
operation will actually give you an ArrayList
, but your code should not depend on it. If the in future there would be designed a better general purpose implementation of the List
interface which will be capable of everything that ArrayList
does, you'll get it for free if you would not demand specifically an ArrayList
. Write your code against interfaces.
Pattern reg = Pattern.compile(",");
List<String> sanr = reg.splitAsStream(joiner.toString())
.filter(role -> role.contains("ABB"))
.map(str -> str.replaceAll("ABB" , ""))
.distinct()
.collect(Collectors.toList());
Sidenote: by convention uppercase-names should be used for constant fields (i.e. marked as final
), for local values use camel-case starting with a lower-case letter. And names by itself should be meaningful, if sanr
is a some kind abbreviation it should be documented somewhere.
CodePudding user response:
If it fits your use case, I would suggest using a Set abstract data type instead of an ArrayList for this purpose. It allows you to not store any duplicates in the list of Strings.
Check out: Java Sets
If you'd like to keep it as an ArrayList you can do:
myArrayList = new ArrayList<String>(new LinkedHashSet<String>(myArrayList));
to delete any duplicates from "myArrayList"