Reputation: 5672
For example, in C# I can select elements from original list:
List<string> result = first_mas.Where(d => d == "1").First().ToList();
And if I remove elements from result
, same elements also will be removed from first_mas
.
In Java I can do something like this:
List<String> result = first_mas.stream().filter(d -> d.equals("1")).collect(Collectors.toList());
But if I remove elements from result
they will not be removed from original array.
Is it possible to remove elements from original list after filtering?
UPD:
public void doSomething(List<String> list){
// here remove something from list, should also be removed from original list
// i don't have link to original list here
}
doSomething(first_mas.stream().filter(d -> d.get(0).equals("1")).collect(Collectors.toList()));
Upvotes: 2
Views: 1785
Reputation: 34460
You should use the Collection.removeIf(predicate)
method.
According to the docs:
Removes all of the elements of this collection that satisfy the given predicate.
In your example:
first_mas.removeIf(d -> d.equals("1"));
Or better:
first_mas.removeIf("1"::equals);
In case you do need to do this inside the doSomething(List<String> list)
method, just pass the original list as an argument.
Upvotes: 0
Reputation: 2271
Probably I do not understand well your question, but why can't you pass the list to doSomething
and then manipulate it with Lambdas?
Something like this:
public static void main(String[] args) {
List<String> l = new ArrayList<>();
l.add("a");
l.add("b");
System.out.println(l.size());
doSomething(l);
System.out.println(l.size());
}
private static void doSomething(List<String> l) {
l.stream().filter(s -> s.equals("a")).findFirst().map(l::remove);
}
Upvotes: 0
Reputation: 6079
You can try this:
List<String> original;
original.removeAll(result);
When you get the result, then you can easily remove all the elements which are in the result List
Upvotes: 3