简体   繁体   English

Java流类型问题

[英]Java stream type issue

Somehow I can't use check on instanceof in stream. 我无法以某种方式在流中对instanceof使用检查。 The problem occurred in test: 测试中出现问题:

ArgumentCaptor<MyClass> arg = ArgumentCaptor.forClass(MyClass.class);
verify(modelService).save(arg.capture());

Method save called three times with different arguments(instances of different classes), and arg.getAllValues() returned SomeOtherClassObject1,SomeOtherClassObject2,MyClassObject 方法save使用不同的参数(不同类的实例)调用了3次,并且arg.getAllValues()返回SomeOtherClassObject1,SomeOtherClassObject2,MyClassObject

Stream bellow throws exception "SomeOtherClass can not be cast to MyClass" 流波纹管引发异常“ SomeOtherClass无法强制转换为MyClass”

MyClass argument = arg.getAllValues().stream()
.filter(v -> v instanceof MyClass)
.findFirst()
.get()

But if I use foreach everything works fine: 但是,如果我使用foreach,一切都会很好:

MyClass argument = null;
for(Object o : arg.getAllValues()) {
    if(o instanceof MyClass) {
        argument = (MyClass) o;
        break;
    }
}

Try with this casting . 尝试这种铸造 Because filter only filtering the stream according to your checking rule. 因为filter仅根据您的检查规则过滤流。 This is one solution to resolve problem. 这是解决问题的一种方法。 Or use map to cast. 或使用map进行投射。

MyClass argument = ((MyClass)arg.getAllValues()
    .stream().
    .filter(v -> v instanceof MyClass)
    .findFirst()
    .get());

PS: map is more relevant to if your results more than one to apply for all. PS:如果您的结果不止一个地适用于所有mapmap更相关。 In your problem casting is more appropriate 在您的问题中更适合投射

The for each loop example shown in the question contains an explicit cast after the instanceof check. 问题中显示的for each循环示例在instanceof检查之后包含一个显式强制转换。 The following would be equivalent to that loop: 以下内容等效于该循环:

MyClass argument =
    arg.getAllValues()
        .stream()                            // Stream<SomeOtherClass>
        .filter(v -> v instanceof MyClass)   // Stream<SomeOtherClass>
        .map(MyClass.class::cast)            // Stream<MyClass>
        .findFirst()                         // Optional<MyClass>
        .orElse(null);                       // MyClass

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

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