简体   繁体   中英

printing the data of list in the order using stream in java

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM