I would like to remove a String entry and an empty String from the Array of Strings.
My array of String contains the following values from index 0 to 3 - 'Name','First','Last', ""
Here is what I tried, using the stream API and Java 11 Predicate.not API:
Arrays.asList(myStringArray).stream()
.filter(Predicate.not(String::isEmpty).or(entry -> entry.equals("Name")))
.collect(Collectors.toList());
I would expect the entries "Name" and "" to be removed from myStringArray, what am I missing?
CodePudding user response:
My question formation may have been poor, sorry about that and here's what I was looking for and it produces the desired result that I need -
Arrays.asList(myStringArray).stream()
.filter(Predicate.not(String::isEmpty)).filter(Predicate.not(entry -> entry.equals("Name")))
.collect(Collectors.toList());
CodePudding user response:
Another possibility:
var newList = new ArrayList<>(Arrays.asList(myStringArray));
newList.removeAll(List.of("", "Name"));
Or, if you know that "Name" is always the first entry and "" is always the last entry, you could do this, which has better performance as it doesn't take any copies of anything:
var newList = Arrays.asList(myStringArray).subList(1, myStringArray.length - 1)
CodePudding user response:
Another way to do this without doing two filter calls can be:
Arrays.asList(myStringArray).stream()
.filter(Predicate.not(String::isEmpty).and(entry -> !entry.equals("Name")))
.collect(Collectors.toList())
CodePudding user response:
I think the problem you have, is that you are not taking resulting list. The thing is, the items are not removed from the array, but new list is created with items without removed items. so just do:
var newList = Arrays.asList(myStringArray).stream()
.filter(Predicate.not(String::isEmpty)).filter(Predicate.not(entry -> entry.equals("Name")))
.collect(Collectors.toList());```