I need to remove some elements from a list inside an hashmap. Old way works. New way won't work, seems do not remove requested elements.
Logging in Old way I never obtain "find after!", as expected. With New way I obtains some "find after!" :(
Old way:
workingMarketCards.forEach((k, v) -> {
for (FixedPriceInsertion fpi : v) {
if (fpi.getMasterId() == oc.getMasterCardId()) {
System.out.println("found before!");
}
}
ArrayList<FixedPriceInsertion> toBeRemoved = new ArrayList<>();
for (FixedPriceInsertion fpi : v) {
if (fpi.getMasterId() == (long) (oc.getMasterCardId())) {
toBeRemoved.add(fpi);
}
}
for (FixedPriceInsertion fpi : toBeRemoved) {
v.remove(fpi);
}
for (FixedPriceInsertion fpi : v) {
if (fpi.getMasterId() == oc.getMasterCardId()) {
System.out.println("found after!");
}
}
});
New way:
workingMarketCards.forEach((k, v) -> {
for (FixedPriceInsertion fpi : v) {
if (fpi.getMasterId() == oc.getMasterCardId()) {
System.out.println("found before!");
}
}
v.stream().filter(s -> s.getMasterId() == (long) (oc.getMasterCardId()));
for (FixedPriceInsertion fpi : v) {
if (fpi.getMasterId() == oc.getMasterCardId()) {
System.out.println("found after!");
}
}
});
Why? What wrong in my code?
.filter()does not remove items from the list, it "returns a stream consisting of the elements of this stream that match the given predicate". look at.removeIf().equals()instead of==when comparing objects.