1

For e.g. I have a List A that has object of class B in it and then class B has a property called as name (String) in it.

Is there any way that I can directly extract the property name to a new List<String> from List A

List<B> A = new ArrayList<>({B1, B2, B3});

now B1 has name = "John" B2 has name = "Michael" B3 has name = "Doe"

Now directly from List A without myself using a for loop can I create a list with all John, Michael and Doe in it.

MadProgrammer
  • 336,120
  • 22
  • 219
  • 344
Nick Div
  • 4,904
  • 9
  • 60
  • 116

1 Answers1

3

If you can use Java8 (and you should since it has been released 15 months ago) you can do it easily with streams:

List<String> names = persons.stream()
.map(p -> p.getName())
.collect(Collectors.toList());
Jack
  • 128,551
  • 28
  • 227
  • 331
  • No, I cannot switch to java 8 yet. I need something like this in the previous version. But I like this approach and I had read about it while learning Java 8. Unfortunately cannot use it as of now. – Nick Div Aug 07 '15 at 07:13