2017-07-06 110 views
0

我有一個Model類的列表。它包含兩個領域:Java按屬性篩選模型列表並返回篩選列表

Class Model { 
    String id; 
    String type; 
} 

我有一個地圖結構: Map<String, List<Model>>每個String表示映射到List<Model>一個名稱。

現在我想檢查名稱是否有明顯的List<Model>。僅當每個模型具有不同的類型時,該列表纔會考慮截然不同。如果有Modal A ("abc", "green"),明年如果我看到Modal B ("dbc", "green")Modal C("drrt", "green"),然後Modal B, Modal C不夠鮮明,我想存儲NameModal B, Modal C,並返回Map<String, List<Modal>>,它代表了名稱,隨着非顯着List<Model>列表;

我想過建立一個Map<String, Set<String>>結構,type爲重點,和Set<id>的值,當我重複了List<Model>,我檢查Map包含了我所看到的鑰匙,如果是,添加idSet ,如果它添加成功,意味着它是不顯着的,我會將它們添加到結果Map<String, List<Modal>>

但是,有沒有其他方法,或者更優雅/簡單/有效的方法來使用它,使用Java庫或Lambda等?請幫忙~~~

+1

你的問題很混亂。試着簡化和清理你的意思。也許使用別的代碼來解釋你的問題。 – Luftbaum

+1

你在找什麼並不難,但你到目前爲止嘗試過什麼?自己寫一些代碼,當有問題時再回來。我們不會爲你寫代碼。 –

回答

0

如何

public class Main { 

    public static void main(String[] args) { 
     Map<String, List<Model>> map = Stream.of(
       new Model("1", "type1"), 
       new Model("2", "type2"), 
       new Model("3", "type2") 
     ) 
       .collect(groupingBy(m -> "name")); 

     Map<String, List<Model>> dupes = map.entrySet().stream() 
       .flatMap(e -> e.getValue().stream() 
         .collect(groupingBy(Model::getType)) 
         .entrySet().stream() 
         .filter(e1 -> e1.getValue().size() > 1) 
         .map(e1 -> new SimpleImmutableEntry<>(e.getKey(), e1.getValue()))) 
       .collect(toMap(Map.Entry::getKey, Map.Entry::getValue)); 

     System.out.println(dupes); 

    } 

    private static class Model { 
     private final String id; 
     private final String type; 

     public Model(String id, String type) { 
      this.id = id; 
      this.type = type; 
     } 

     public String getId() { 
      return id; 
     } 

     public String getType() { 
      return type; 
     } 

     @Override 
     public String toString() { 
      return "Model{" + 
        "id='" + id + '\'' + 
        ", type='" + type + '\'' + 
        '}'; 
     } 
    } 
} 

打印{名= [產品型號{ID = '2',類型= '2型'},{型號ID = '3',類型='2型'}]}