How can I throw CHECKED exceptions from inside Java 8 streams?

前端 未结 18 1812
你的背包
你的背包 2020-11-22 06:59

How can I throw CHECKED exceptions from inside Java 8 streams/lambdas?

In other words, I want to make code like this compile:

public List

        
18条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 07:40

    Here is a different view or solution for the original problem. Here I show that we have an option to write a code that will process only a valid subset of values with an option to detect and handle caseses when the exception was thrown.

        @Test
        public void getClasses() {
    
            String[] classNames = {"java.lang.Object", "java.lang.Integer", "java.lang.Foo"};
            List classes =
                    Stream.of(classNames)
                            .map(className -> {
                                try {
                                    return Class.forName(className);
                                } catch (ClassNotFoundException e) {
                                    // log the error
                                    return null;
                                }
                            })
                            .filter(c -> c != null)
                            .collect(Collectors.toList());
    
            if (classes.size() != classNames.length) {
                // add your error handling here if needed or process only the resulting list
                System.out.println("Did not process all class names");
            }
    
            classes.forEach(System.out::println);
        }
    

提交回复
热议问题