Myoch
Myoch

Reputation: 855

Passing and casting a Comparator as argument of method using Lambdas

How can I create a method that would accept a comparator with wildcard as argument, and then capture the class and use the comparator ?

public List<String> myFilter(Comparator<?> comp, Object value, Class c){
   return myList.stream()
         .filter(s->
              comp.compare(c.cast(s), c.cast(value))>=0
          ).collect(toList());
  }

EDIT: Ok, In fact, Andrew's answer is very interesting and works quite well :) Yet,given the comments, what I really should want is: instead of trying to cast within the method, expect that the cast had already been done within the comparator

so this would give:

  public List<String> filter(Comparator<String> comp){
         return myList.filter(s->comp.compare(s, null)>=0).collect(toList());
   }

and when calling it, this should be something like

   List<String> myNewList= filter((String s1, String s2)->{
                  try{
                      int i=Integer.parseInt(s1);
                      return Integer.compare(i, myRealCompareValue);
                 }catch(Exception e){
                      e.printStackTrace();
                     return null;
                 });

It doesn't look very nice though....

Upvotes: 2

Views: 2275

Answers (1)

Myoch
Myoch

Reputation: 855

In fact, my question was a possible duplicate of How do I define a method which takes a lambda as a parameter in Java 8?

and what I really wanted to do was

 public List<String> myFilter(MyComparator c){
        return myList
           .stream()
           .filter(c::compare)
           .collect(toList());
 }

with and interface MyComparator:

  public interface MyComparator{
        public boolean compare(String s);
  }

and then this could be called:

   List<String> myNewList=filter((String s)->s.compareTo(whateverString)>=0);

or even:

   List<String> myNewList=filter((String s)->{
           try{
               return Integer.compare(Integer.parseInt(s), 10)>=0;
           }catch(Exception e){
               return false;
           });

Upvotes: 1

Related Questions