Copying an attribute from a list in java

Asked

Viewed 71 times

0

Copy example:

List<MyObject> listaDeObjetos = new ArrayList<>();

List<String> nomes = new ArrayList<>();
for (MyObject obj : listaDeObjetos) {
   nomes.add(obj.getNome());
}

There’s something in java that makes this easy?

  • Facilitate in what sense?

  • Not that I know of. If this is very constant in your code, I advise you to extract the logic for a method (static or Abstract class) so that you can reuse your logic.

  • What version of Java? Until the 7, I believe that there is nothing to simplify this, the way you are doing seems ideal. From the 8, with the support of Amble, there should be a simpler and more concise way to do what you want, but I don’t know how. Maybe you’ll find some useful information in the question "How to use Bilges and stream?"

1 answer

5


In Java 8 it is possible to do this by using streams:

List<MyObject> listaDeObjetos = new ArrayList<>();

List<String> nomes = listaDeObjetos.stream().map(MyObject::getNome)
                     .collect(Collectors.toList());

I don’t know the exact type of list that this Collectors.toList() is returning. If you really need it to be a ArrayList, can replace it with toCollection:

                     .collect(Collectors.toCollection(ArrayList::new));

Finally, if your list is too long maybe compensate for replacing the stream() for parallelStream(), so that Java can distribute the processing across multiple cores (in this simple case it is likely not to compensate).

I don’t know anything in Java 7 or earlier that can facilitate this task, the simplest is to make a loop even, as you are already doing. By the way, in the "performance" category I believe (but have not tested) that your loop is faster than the use of streams, and in this simple case one is as concise as the other.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.