Sample Copy:
List<MyObject> listaDeObjetos = new ArrayList<>();
List<String> nomes = new ArrayList<>();
for (MyObject obj : listaDeObjetos) {
nomes.add(obj.getNome());
}
Is there anything in java that makes this easy?
Sample Copy:
List<MyObject> listaDeObjetos = new ArrayList<>();
List<String> nomes = new ArrayList<>();
for (MyObject obj : listaDeObjetos) {
nomes.add(obj.getNome());
}
Is there anything in java that makes this easy?
In Java 8 you can do this by using streams : / p>
List<MyObject> listaDeObjetos = new ArrayList<>();
List<String> nomes = listaDeObjetos.stream().map(MyObject::getNome)
.collect(Collectors.toList());
I do not know what exact type of the list this Collectors.toList()
is returning. If you really need to be ArrayList
, you can replace it with toCollection
:
.collect(Collectors.toCollection(ArrayList::new));
Finally, if your list is too large maybe compensate replace stream()
with parallelStream()
, so Java can distribute multi-core processing (in this case simple do not make up).
I do not know anything about Java 7 or earlier that might make it easier, but the simplest thing is to do a loop, just like you already do. By the way, in the "performance" question I believe (but have not tested) that your loop is faster than the use of streams, and in that case, one is as concise as the other.