Javaの(8):オブジェクトの配列から特定のクラスの項目を抽出する方法は?

dushkin:

私は、次の値を持つオブジェクトの配列で作業する必要があります。

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

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=185331&siteId=1