简体   繁体   中英

converting list of one type to another in java

I have a list of type File which I need to convert to another type. But it is giving an error Attempt to invoke interface method 'java.util.stream.Stream java.util.List.stream()' on a null object reference .

I have this non empty list "files" which I want to convert

List<File> files = FileUtils.listFilesInDirWithFilter(directory,fileFilter,true);

List<MyClass> customer = files.stream()
                            .filter(MyClass.class::isInstance)
                            .map(MyClass.class::cast)
                            .collect(Collectors.toList());

Is there any way that I can change it to my required type?

I think you can use this one:

files.stream()
        .map(aClass -> instantiateClass(aClass, "message"))
        .filter(Objects::nonNull)
        .findFirst()
        .orElseThrow(() -> new CustomException("blabla"));

Method instantiateClass :

private MyClass instantiateClass(final Class<?> aClass, final String message) {
MyClass returnedClass= null;
try {
  returnedClass = (MyClass) aClass
      .getDeclaredConstructor(String.class) // should contain the same parameters count and types like your constructor in MyClass
      .newInstance(message);
} catch (Exception e) {
  log.error("The declared constructor for class {} was not found", aClass.getName());
}
return returnedClass;
}

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