2

I am wondering if there's a better way to rewrite the groupA method with lambda as part of the chaining operations ?

public class Id {
    private final int value;
    public Id(int value) {
       this.value = value;
    }

    public int value() {
       return value;
    }
}

public class Ids implements Iterable<Id> { 
   private final List<Id> ids;

   private Ids(List<Id> ids) {
      this.ids = ids;
   }

   public static Ids of(List<Id> ids) {
      return new Ids(ids);
   }

   public Ids groupA() {
      return Ids.of(ids.stream()
                       .filter(id -> id.value() > 5)
                       .collect(Collectors.toList()));
   }

   @Override
   public Iterator<Id> iterator() {
      return ids.iterator();
   }
}

Basically I want to do something like

ids.stream()
   .filter(id -> id % 10 > 5)
   .collect(Collectiors.toList())
   .andThen(Ids::of);

And wonder if that's possible

0

2 Answers 2

10

Sure. You can either just do the straightforward

Ids.of(ids.stream()
   .filter(id -> id % 10 > 5)
   .collect(Collectors.toList()))

or you could add it to the collector:

ids.stream()
   .filter(id -> id % 10 > 5)
   .collect(Collectors.collectingAndThen(Collectors.toList(), Ids::of))
Sign up to request clarification or add additional context in comments.

9 Comments

when I do option2 which is the one that uses collectingAndThen that the compiler explains having problem resolving method 'of'
@peter what is the exact error? It looks like the types aren't quite right, since you can't do id % 10 with id of type Id.
Though the static method is not necessary in this context. Here, Ids::of could be replaced by Ids::new. Besides that, @peter what’s wrong with the original approach?
@peter I don't get that error when I actually plug this into a compiler. ideone.com/pr1ryb
@peter the first one performs a tiny bit better, since you're not allocating the Collector or the lambda. The JIT might be able to optimize that away, but if it doesn't improve readability what's the point?
|
2

In my StreamEx library there's a shortcut method toListAndThen which makes this looking more fluent:

StreamEx.of(ids)
  .filter(id -> id % 10 > 5)
  .toListAndThen(Ids::of);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.