Java 8 Lambdas - equivalent of c# OfType

后端 未结 4 1567
悲&欢浪女
悲&欢浪女 2021-02-19 14:52

I am learning the new java 8 features now, after 4 years exclusively in C# world, so lambdas are on top for me. I am now struggling to find an equivalent for C#\'s \"OfType\" me

4条回答
  •  无人共我
    2021-02-19 15:15

    I was having the same issue. This is what I came up with, but since java doesn't do extension methods (maybe in 10 more years?), it is a static method. This is using the stream API, though there isn't a particular reason you must do that. The same basic checks would work just fine in a for loop with a preallocated ArrayList.

    @SuppressWarnings("unchecked")
    private static  List ofType(Class out, List list) {
        return list.stream().filter(x -> out.isAssignableFrom(x.getClass()))
                   .map(x -> (T) x) // unchecked
                   .collect(Collectors.toList());
    }
    
    // fyi this code uses "boon" library
    List objlist = list("ABC", 3, "def", -30.39); 
    puts("strings=", ofType(String.class, objlist));  // strings= [ABC, def] 
    puts("integers=", ofType(Integer.class, objlist)); // integers= [3]
    
    
    

    Here is the version that doesn't use streams. It works just the same, but some of the fun with streams is that ... you might be able to stream them, if thats your kind of thing. I don't find it useful very often except for helpers like this.

    private static  List ofType(Class out, List list) {
        List outList = new ArrayList(list.size());
        for(Object o : list) {
            if ( out.isAssignableFrom(o.getClass())) {
                outList.add((T)o);
            }
        }
        return outList;
    }
    
        

    提交回复
    热议问题