简体   繁体   English

使用Lambdas传递并强制将Comparator作为方法的参数

[英]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.... 虽然看起来不太好....

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? 实际上,我的问题是“ 如何定义在Java 8中以lambda作为参数的方法”的可能重复项

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: 与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;
           });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM