If you want to assign null to the age also when it has low size then it can't achieve with int data type.
Solution 1:
assign null to both name or age if the value is not there
you need to change the type of age to String
List<String> names = List.of("Mike", "Piter", "Jack");
List<String> ages = List.of("18", "29");
List<Person> collect = null;
if (names.size() > ages.size()) {
collect = IntStream.range(0, names.size())
.mapToObj(i -> new Person(names.get(i), (i < ages.size() ? ages.get(i) : null)))
.collect(Collectors.toList());
} else {
collect = IntStream.range(0, ages.size())
.mapToObj(i -> new Person(i < names.size() ? names.get(i) : null, ages.get(i)))
.collect(Collectors.toList());
}
System.out.println(collect);
Solution 2:
assign null to name and -1 to age if the value is not there
List<String> names = List.of("Mike", "Piter", "Jack");
List<Integer> ages = List.of(18, 29);
List<Person> collect = null;
if (names.size() > ages.size()) {
collect = IntStream.range(0, names.size())
.mapToObj(i -> new Person(names.get(i), (i < ages.size() ? ages.get(i) : -1)))
.collect(Collectors.toList());
} else {
collect = IntStream.range(0, ages.size())
.mapToObj(i -> new Person(i < names.size() ? names.get(i) : null, ages.get(i)))
.collect(Collectors.toList());
}
System.out.println(collect);