Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java streams: merge/map collections

I've this class:

private class Item {
  private String transactionId;
  private String user;
  private LocalDate expiration;
  private String confidential;
  private String locked;
}

By other hand, I've five collections:

List<String> transactions;
List<String> users;
List<LocalDate> expirations;
List<String> confidential;
List<String> lockeds;

So I need to map each n of each collection to a new Item object.

Any ideas?

like image 639
Jordi Avatar asked Dec 23 '22 03:12

Jordi


1 Answers

Stream over the indices (assuming all 5 lists have the same number of elements):

List<Item> items = IntStream.range(0,transactions.size())
                            .mapToObj(i -> new Item(transactions.get(i),
                                                    users.get(i),
                                                    expirations.get(i),
                                                    confidential.get(i),
                                                    lockeds.get(i)))
                            .collect(Collectors.toList());
like image 91
Eran Avatar answered Jan 08 '23 10:01

Eran