合併多個相同物件內的List物件 物件設定

@Data
public class TestTOB {
  private List type;

  public static class Sel {
    private String key;
    private String val;

    /**
     * @param a
     * @param b
     */
    public Sel(String key, String val) {

      super();
      this.key = key;
      this.val = val;
    }

    @Override
    public String toString() {

      StringBuilder builder = new StringBuilder();
      builder.append("Sel [key=").append(key).append(", val=").append(val).append("]");
      return builder.toString();
    }

  }
}

用flatMap將TestTOB內的List轉換成個別扁平流,再透過collect結合

  @Test
  public void flatMapTest() throws Exception {
    List a= new ArrayList<>();
    
    TestTOB qq = new TestTOB();
    qq.setType(Collections.singletonList(new TestTOB.Sel("a","1")));
    a.add(qq);
    
    qq = new TestTOB();
    qq.setType(Collections.singletonList(new TestTOB.Sel("b","2")));
    a.add(qq);
    
    qq = new TestTOB();
    qq.setType(Collections.singletonList(new TestTOB.Sel("c","3")));
    a.add(qq);
    
    List c = a.stream()
        .flatMap(o -> o.getType().stream())
        .collect(Collectors.toList());
    
    c.stream().forEach(o->System.out.println(o.toString()));

  }
  
//Sel [key=a, val=1]
//Sel [key=b, val=2]
//Sel [key=c, val=3]

 

arrow
arrow

    咪卡恰比 發表在 痞客邦 留言(0) 人氣()