简体   繁体   中英

Java8 lambda predicate exception

I have the follow lambda expression:

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 .

I'd like to raise the exception to the main function mylambdafunction() , somethings like:

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 .

Use StandardCharsets.UTF_16LE as the Charset argument.


Stream#filter(Predicate) expects a Predicate which provides a test(Object) method. 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. Similarly, any method reference to a method that declares such an exception will also be incompatible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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