How to call a parameterized getter a mapper in a Java 8 stream?

Use case

I currently have this pattern in many adapters:

entries.stream()
        .filter(Entry.class::isinstance)
        .map(Entry.class::cast)
        .map(Entry::getFooBar)
        .collect(Collectors.toList());

An entry is a list of objects that implement a specific interface Unfortunately, the interface - which is part of a third-party library - does not define a common getter To create the list of objects I want, I need to search them, project them, and call the appropriate getter method

I'm going to refactor it into a help class:

public static <T,O> List<O> entriesToBeans(List<T> entries,Class<T> entryClass,supplier<O> supplier) {
    return entries.stream()
            .filter(entryClass::isinstance)
            .map(entryClass::cast)
            .map(supplier)                  // <- This line is invalid
        .collect(Collectors.toList());
}

Then I call this method to convert:

Helper.entriesToBeans(entries,Entry_7Bean.class,Entry_7Bean::getFooBar);

Unfortunately, I can't pass a getter to the refactoring function and have the map call it because the map needs a function

topic

> How do I call getter in the refactoring version?

Solution

Methods like this:

class T {
  public O get() { return new O(); }
}

Map to function < T, O >

Therefore, you only need to change the method signature to:

public static <T,Function<T,O> converter) {

Update: I suspect that the reason for projection is that your original list may contain elements that are not ts So you can also change the signature to:

public static <T,O> List<O> entriesToBeans(List<?> entries,O> converter) {

Then, you can pass list < Object >, for example, keep only ts, transformation and transformation in the list

For reference, this is a working example (print John, Fred):

static class Person {
  private final String name;
  Person(String name) { this.name = name; }
  String name() { return name; }
}

public static void main(String[] args) {
  List<String> result = entriesToBeans(Arrays.asList(new Person("John"),new Person("Fred")),Person.class,Person::name);
  System.out.println("result = " + result);
}

public static <T,O> converter) {
  return entries.stream()
          .filter(entryClass::isinstance)
          .map(entryClass::cast)
          .map(converter)
          .collect(Collectors.toList());
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>