gpt4 book ai didi

java - 有没有办法将 stream().collect() 1 项分成 2 组?

转载 作者:行者123 更新时间:2023-12-04 12:28:46 25 4
gpt4 key购买 nike

我的目标是将包和子包中的类分组到 Map<ClassAnnotationType, List<Class> map 中。 @usage 例如 map.get(ClassAnnotationType.RestController)我所做的:

  • 获取包和子包中的所有类。 Stack Overflow's question

  • 类注解类型
    public enum ClassAnnotationType {
    RestController,
    Service,
    Unknown
    }
    类注释列表
    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    public @interface RestController{
    }

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.TYPE)
    public @interface Service {
    }
    这就是搜索树的工作方式
      /**
    * .class .class package package
    * / \ (first iteration) / \ (second iteration)
    * .class .class package .class .class package
    * / \ (first iteration) / \ (second iteration)
    */
    这是我希望更改的代码行
      private Map<Boolean, List<String>> getResources(String packageName) {
    InputStream inputStream = ClassLoader.getSystemClassLoader()
    .getResourceAsStream(packageName.replaceAll("[.]", "/"));
    BufferedReader bufferedReader = new BufferedReader(
    new InputStreamReader(inputStream));
    return bufferedReader.lines()
    .map(i -> packageName.concat("." + i))
    .collect(Collectors.partitioningBy(i -> i.endsWith(".class")));
    }
    变成这样
    .collect(
    Collectors.groupingBy(i -> {
    for (Annotation annotation : i.getAnnotations()) {
    // add the Class to the key.
    }
    }));
    我的预期结果:Collectors.groupingBy() 可以将 1 个项目 class Hello 添加到 2 个不同的组中,例如 RestController, Service我的实际结果:1 组 1 项。
    当前预解决方案
    .collect(i -> {
    if (i.isAnnotationPresent(RestController.class)) {
    return ClassAnnotationType.RestController;
    }
    return ClassAnnotationType.Unknown; // i wish not to do this.
    });
    这产生了问题:
  • 1 个类只能存在于 1 个组中。
  • 由于 ClassLoader.getSystemClassLoader().getResourceAsStream() 的性质,它将在包内返回 class class package。当前代码必须首先列出树并将其映射到 String ,然后再使用 Class 方法将其类型转换为 Class.forName() 。换句话说,唯一可行的方法是分三步完成。一种。得到一个包和子包中的所有类,递归到 List<String> b。将其类型转换为 List<Class> c。将其映射到 Map<ClassAnnotationType, List<Class>
  • 所有的类都需要映射成一个key,包括没有注解的类 return ClassAnnotationType.Unknown
  • 最佳答案

    您可以使用自定义 Collector 来做到这一点。 , 与 Collector.of .也许是这样的:

    Collector.of(
    // Supplier.
    HashMap::new,

    // Accumulator.
    (map, i) -> {
    // Your code. You can put whatever you like into the map,
    // so you can put something in for multiple keys.
    for (Annotation annotation : i.getAnnotations()) {
    // add the Class to the key.
    }
    },

    // Combiner.
    (map1, map2) -> { map1.putAll(map2); return map1; }
    )

    关于java - 有没有办法将 stream().collect() 1 项分成 2 组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68498886/

    25 4 0