Skip to content
Advertisement

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

I need to work on an Objects array which has the following value:

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} 

The code which creates the objects array is:

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();

I need to extract a value from the ApplicationConfiguration type item.

Note that it is not always the first array item!

For start, I tried to do the following:

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

in order to get a list with the specific item. For some reason I got an empty list.

Why?

Advertisement

Answer

objectsArray contains map entries, and you need to filter the values of those entries.

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());

Of course, it would be cleaner if you changed

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

to

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

so that you can write:

List<ApplicationConfiguration> ApplicationConfigurations = 
    Arrays.stream(objectsArray)
          .filter(e -> e.getValue() instanceof ApplicationConfiguration)
          .map(e -> (ApplicationConfiguration) e.getValue())
          .collect(Collectors.toList());
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement