简体   繁体   English

Java8 Lambda谓词异常

[英]Java8 lambda predicate exception

I have the follow lambda expression: 我有以下lambda表达式:

public mylambdafunction(){
Optional<MyClass> optional = Arrays.stream(myClassesValues).filter(x ->
   new String(x.bytesArray,"UTF-16LE").equalsIgnoreCase(comparationString)).findFirst();
}

Well, the method new String(x.bytesArray,” UTF-16LE”) raise the Exception UnsupportedEncodingException . 好吧,方法new String(x.bytesArray,” UTF-16LE”)引发异常UnsupportedEncodingException

I'd like to raise the exception to the main function mylambdafunction() , somethings like: 我想对主要函数mylambdafunction()引发异常,如下所示:

public mylambdafunction() throws UnsupportedEncodingException{ 
....
}

Is that possible? 那可能吗?

An alternative to potentially modifying a functional interface method, since you are using a well known character set, is to use the overloaded String constructor which accepts a byte[] and a Charset , but which doesn't throw UnsupportedEncodingException . 因为您使用的是众所周知的字符集,所以可能修改功能接口方法的另一种方法是使用重载的String构造函数,该构造函数接受byte[]Charset ,但不抛出UnsupportedEncodingException

Use StandardCharsets.UTF_16LE as the Charset argument. 使用StandardCharsets.UTF_16LE作为Charset参数。


Stream#filter(Predicate) expects a Predicate which provides a test(Object) method. Stream#filter(Predicate)需要一个提供test(Object)方法的Predicate Since this method does not declare a checked exception which is a supertype of UnsupportedEncodingException (and since UnsupportedEncodingException is itself checked), then any lambda expression whose body throws such an exception will be incompatible. 由于此方法未声明作为UnsupportedEncodingException的超类型的检查异常(并且由于UnsupportedEncodingException本身已被检查),因此任何正文引发此类异常的lambda表达式都是不兼容的。 Similarly, any method reference to a method that declares such an exception will also be incompatible. 同样,对声明此类异常的方法的任何方法引用也将不兼容。

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

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