Fill list with another object list

时间:2016-10-20 12:39:56

标签: java arraylist java-8 java-stream

Is there any convenient way to move/copy id's from objList to idList?

With java 8 streams maybe?

public class SomeObject() {
  private Long id;
  private String value;

  public Long getId() { return id; }
  public void setId(Long id) { this.id = id; }
  public String getValue() { return value; }
  public void setValue(String value) { this.value = value; }
}

Somewhere in code:

public void doSomething() {

  List<SomeObject> objList = fillWithManyObjects(); //getting objects with values
  List<Long> idList = new ArrayList<Long>();

  objList.forEach(obj -> flightSlotIdSet.add(obj.getId));

}

1 个答案:

答案 0 :(得分:6)

Its a simple stream

 List<Long> idList = objList.stream()
     .map(SomeObject::getId)
     .collect(Collectors.toList())