1

I'm new to java8.
I have the following classes.

class User {
  List<Vehicle> vehicle;
  private int vehiclecount;

  public List<Vehicle> getVehicle() {
        return vehicle;
  }
}

class Vehicle{
  String vehiclename;
  String vehiclecolor;
}

I am able to save this in mongo collection:

{ "_id" : ObjectId("59ca1e53a1a79607fcc9200f"), "_class" : "com.test.User", 
   "vechicle" : [ { "vehiclename" : "Car", "vehiclecolor" : "Blue" } ], 
   "count" : 1, "createdDate" : ISODate("2017-09-26T09:30:59.826Z") } 

Now i pulled out the result based on spring mongo data repository. i want to iterate the above mongo collection so that i can only get the vehicle list I tried the below:

List<Vehicle> vehicle = result.stream().filter(vehicles->vehicles.getVehicle().stream().collect(Collectors.toList());

Please help im new to java8. Thanks in advance

Naxos84
  • 1,890
  • 1
  • 22
  • 34
user24393
  • 21
  • 5
  • 1
    `result` is a collection of users? and you want to obtain a collection of vehicles? – Eugene Sep 27 '17 at 10:31
  • yes absolutely , result is a collection of users. – user24393 Sep 27 '17 at 10:32
  • 1
    Possible duplicate of [What is the proper way of replacing a nested for loop with streams in Java 8?](https://stackoverflow.com/questions/27174700/what-is-the-proper-way-of-replacing-a-nested-for-loop-with-streams-in-java-8) – user140547 Sep 27 '17 at 10:44

1 Answers1

4

If I understood correctly:

List<Vehicle> vehicles = 
    result.stream()
       .flatMap(user -> user.getVehicle().stream())
       .collect(Collectors.toList());
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
Eugene
  • 117,005
  • 15
  • 201
  • 306
  • works like charm.. Thanks Eugune.. solved the problem. – user24393 Sep 27 '17 at 10:40
  • sure ..definately. intially i accepted but it asked to wait for some time to accept an answer. – user24393 Sep 27 '17 at 10:43
  • But when i try to iterate the list vehicles, im getting the entire vehicle object itself (result == com.test.Vehicle@17220255), i want to retrieve vehiclename and vehiclecolor of the vehicle. Below is my code: vehicles.forEach(result->System.out.println("result == "+result)); – user24393 Sep 27 '17 at 11:04
  • sorry missed to retrieve the properties from result object.vehicles.forEach(result->System.out.println("result == "+result.getvehiclename()+" color>>"+result.getvehiclecolor())); – user24393 Sep 27 '17 at 11:25
  • is there a way to retrieve the "_id" field from the result stream? – user24393 Sep 27 '17 at 13:17