omerhakanbilici omerhakanbilici - 1 month ago 5
Java Question

Fill list with another object list

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

}

Answer

Its a simple stream

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