72

Like just about everyone, I'm still learning the intricacies (and loving them) of the new Java 8 Streams API. I have a question concerning usage of streams. I'll provide a simplified example.

Java Streams allows us to take a Collection, and use the stream() method on it to receive a stream of all of its elements. Within it, there are a number of useful methods, such as filter(), map(), and forEach(), which allow us to use lambda operations on the contents.

I have code that looks something like this (simplified):

set.stream().filter(item -> item.qualify())
    .map(item -> (Qualifier)item).forEach(item -> item.operate());
set.removeIf(item -> item.qualify());

The idea is to get a mapping of all items in the set, which match a certain qualifier, and then operate through them. After the operation, they serve no further purpose, and should be removed from the original set. The code works well, but I can't shake the feeling that there's an operation in Stream that could do this for me, in a single line.

If it's in the Javadocs, I may be overlooking it.

Does anyone more familiar with the API see something like that?

8 Answers 8

124

You can do it like this:

set.removeIf(item -> {
    if (!item.qualify())
        return false;
    item.operate();
    return true;
});

If item.operate() always returns true you can do it very succinctly.

set.removeIf(item -> item.qualify() && item.operate());

However, I don't like these approaches as it is not immediately clear what is going on. Personally, I would continue to use a for loop and an Iterator for this.

for (Iterator<Item> i = set.iterator(); i.hasNext();) {
    Item item = i.next();
    if (item.qualify()) {
        item.operate();
        i.remove();
    }
}
5
  • 12
    +1 for using a for loop; don't use streams just so you can fit your code on one line. Loops are often more readable than streaming solutions, even if they're more verbose.
    – dimo414
    May 4, 2015 at 23:39
  • 4
    I'm a little hesitant to insert state-altering code into removeIf(), though I believe this would theoretically work. Additionally, my situation lends itself to functional programming, so my need for streams goes beyond packing everything into a single line; but thank you. May 5, 2015 at 0:20
  • 3
    Using removeIf with lambda expression is perfectly legit and it's supposed to be used that way. State altering is part of collection API not stream.
    – hussachai
    Nov 3, 2015 at 6:15
  • 7
    good example with the for loop, however why do you think it is more clear? for me I actually think that, in this case, the stream solution is more clear
    – serup
    Jul 5, 2016 at 6:59
  • I really like that iterator snippet.
    – Kamil
    Mar 2, 2019 at 3:09
4

In one line no, but maybe you could make use of the partitioningBy collector:

Map<Boolean, Set<Item>> map = 
    set.stream()
       .collect(partitioningBy(Item::qualify, toSet()));

map.get(true).forEach(i -> ((Qualifier)i).operate());
set = map.get(false);

It might be more efficient as it avoids iterating the set two times, one for filtering the stream and then one for removing corresponding elements.

Otherwise I think your approach is relatively fine.

1
  • Where's the remove in the answer? What am I missing here? Mar 31, 2018 at 12:00
4

There are many approaches. If you use myList.remove(element) you must override equals(). What I prefer is:

allList.removeIf(item -> item.getId().equals(elementToDelete.getId()));

Good luck and happy coding :)

1
  • note that this will remove only the first occurrence that matches the predicate Mar 12, 2019 at 11:00
3

After the operation, they serve no further purpose, and should be removed from the original set. The code works well, but I can't shake the feeling that there's an operation in Stream that could do this for me, in a single line.

You cannot remove elements from the source of the stream with the stream. From the Javadoc:

Most stream operations accept parameters that describe user-specified behavior..... To preserve correct behavior, these behavioral parameters:

  • must be non-interfering (they do not modify the stream source); and
  • in most cases must be stateless (their result should not depend on any state that might change during execution of the stream pipeline).
0
2

What you really want to do is to partition your set. Unfortunately in Java 8 partitioning is only possible via the terminal "collect" method. You end up with something like this:

// test data set
Set<Integer> set = ImmutableSet.of(1, 2, 3, 4, 5);
// predicate separating even and odd numbers
Predicate<Integer> evenNumber = n -> n % 2 == 0;

// initial set partitioned by the predicate
Map<Boolean, List<Integer>> partitioned = set.stream().collect(Collectors.partitioningBy(evenNumber));

// print even numbers
partitioned.get(true).forEach(System.out::println);
// do something else with the rest of the set (odd numbers)
doSomethingElse(partitioned.get(false))

Updated:

Scala version of the code above

val set = Set(1, 2, 3, 4, 5)
val partitioned = set.partition(_ % 2 == 0)
partitioned._1.foreach(println)
doSomethingElse(partitioned._2)`
4
  • Ah, hopefully they'll implement a "forEachAndRemove" method one of these days. I don't think that my code would be any clearer, or any faster, if I did that. Thank you for the help! May 5, 2015 at 0:14
  • Surprisingly you do not need specific methods like that. The same code in Scala makes a lot more sense (see above). May 5, 2015 at 3:46
  • Where's the remove in the answer? What am I missing here? Mar 31, 2018 at 12:00
  • @AlikElzin-kilaka elements in the List partitioned.get(false) are the removed ones, and the list in partitioned.get(true) is what remains of the original List after removal. If I got it right. Feb 6, 2019 at 22:57
1

Nope, your implementation is probably the simplest one. You might do something deeply evil by modifying state in the removeIf predicate, but please don't. On the other hand, it might be reasonable to actually switch to an iterator-based imperative implementation, which might actually be more appropriate and efficient for this use case.

1
  • I've been thinking about that, but for my actual (unsimplified) implementation, the streams could get to be enormous. I'm running this generally on four to eight core machines; so in spite of the youth of Java's Stream API I am not yet convinced that iterators will be a benefit. parallel() could be a saviour here. Thank you for the prompt response, though! May 5, 2015 at 0:17
1

if I understand your question correctly:

set = set.stream().filter(item -> {
    if (item.qualify()) {
        ((Qualifier) item).operate();
        return false;
    }
    return true;
}).collect(Collectors.toSet());
0

I see Paul's clarity concern when using streams, stated in the top answer. Perhaps adding explaining variable clarifies intentions a little bit.

set.removeIf(item -> {
  boolean removeItem=item.qualify();
  if (removeItem){
    item.operate();
  }
  return removeItem;
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.