Home > Back-end >  printing the data of list in the order using stream in java
printing the data of list in the order using stream in java

Time:08-16

I have below List.

List<String> firstName = List.of("Monika","Shweta", "Shruti","Anuradha");
List<String> lastName = List.of("Mishra","Hariharno","Sharma","Mishra");
List<Integer> sal = List.of(5000000,50,500,100000);

List<List<?>> finalList = List.of(firstName,lastName,sal);
finalList.stream().flatMap(s->s.stream()).forEach(System.out::println);

When I am printing using flatMap() it is printing all firstname, lastname, and then sal.

I want to print firstName : lastName:sal together for all of them in order. for eg

Monika:Mishra:5000000

is it possible using flatMap or any other java8 feature?

CodePudding user response:

Yes, it is possible but I wouldn't recommend it:

List<List<?>> result = IntStream.range(0, sal.size())
        .mapToObj(i -> List.of(firstName.get(i), lastName.get(i), sal.get(i)))
        .collect(Collectors.toList());

Instead, create some type to represent your objects.

CodePudding user response:

If you need to do this in one list, you can set up a class containing all your data. Then create a list of your custom objects and print each field in the forEach

  • Related