我需要处理具有以下值的 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/

10-10 12:53