Java(8) : How to extract an specific class item from objects array?

标签 java java-8

我需要处理具有以下值的 Objects 数组:

objectsArray = {Object[3]@10910} 
 {Class@10294} "class com.ApplicationConfiguration" -> {ApplicationConfiguration@10958} 
    key = {Class@10294} "class com.ApplicationConfiguration"
    value = {ApplicationConfiguration@10958} 
 {Class@10837} "class com.JoongaContextData" -> {JoongaContextData@10960} 
    key = {Class@10837} "class com.JoongaContextData"
    value = {JoongaContextData@10960} 
 {Class@10835} "class com.SecurityContext" -> {SecurityContext@10961} 
    key = {Class@10835} "class com.SecurityContext"
    value = {SecurityContext@10961} 

创建对象数组的代码是:

public class ProcessDetails {
    private UUID myId;
    private Date startTime;
    private ResultDetails resultDetails;
    private long timeout;
    .
    .
    .
}

public interface ProcessStore extends Map<Class, Object> {
    <T> T unmarshalling(Class<T> var1);

    <T> void marshalling(T var1);

    ProcessDetails getProcessDetails();
}

Object[] objectsArray = processStore.entrySet().toArray();

我需要从 ApplicationConfiguration 类型的项目中提取一个值。

请注意,它并不总是第一个数组项!

首先,我尝试执行以下操作:

    List<ApplicationConfiguration> ApplicationConfigurations = Arrays.stream(objectsArray)
            .filter(item -> item instanceof ApplicationConfiguration)
            .map(item -> (ApplicationConfiguration)item)
            .collect(Collectors.toList());

为了获得包含特定项目的列表。 出于某种原因,我得到了一个空列表。

为什么?

最佳答案

objectsArray 包含映射条目,您需要过滤这些条目的值。

List<ApplicationConfiguration> ApplicationConfigurations = 
    Arrays.stream(objectsArray)
          .map(obj -> (Map.Entry<Class, Object>) obj)
          .map(Map.Entry::getValue)
          .filter(item -> item instanceof ApplicationConfiguration)
          .map(item -> (ApplicationConfiguration)item)
          .collect(Collectors.toList());

当然,如果你改一下就更干净了

 Object[] objectsArray = processStore.entrySet().toArray();

 Map.EntryMap.Entry<Class,Object>[] objectsArray = processStore.entrySet().toArray(new Map.Entry[0]);

这样你就可以写:

List<ApplicationConfiguration> ApplicationConfigurations = 
    Arrays.stream(objectsArray)
          .filter(e -> e.getValue() instanceof ApplicationConfiguration)
          .map(e -> (ApplicationConfiguration) e.getValue())
          .collect(Collectors.toList());

关于Java(8) : How to extract an specific class item from objects array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56251385/

相关文章:

java - 迁移到 Java 8 后运行 jnlp 文件

java - Spring Boot 配置是否带有预设默认值?

java - Unix/Linux 中的 JVM 内存管理

java - 用扭曲遍历一个无向、未加权的图 : minimum visits to each node

java - android中读取xml标签属性

java - 将 ArrayList<Integer> 存储为 TreeMap Java 中的键

datetime - JPA2 标准和 Java 8 日期和时间 API

java - 在流中使用 Java 8 foreach 循环移至下一项

java - 在JDK8中,我可以只使用一个流表达式来获得两个条件的结果吗?

java - 使用过滤器和流将 Map<String, Object> 转换为 Map<String, Set<Object>>