Assert that the two lists have the same length. Create a list of all names and surnames



  1. Assert that the two lists have the same length. Done
  2. Create a list of all names and surnames. Done
  3. Is there any better way to do this ? or can the code be reduced? —> I need help.
    static List<String> ex2(List<String> names, List<String> surnames) {
        if (names.size() != surnames.size()) {
    throw new IllegalArgumentException("the two lists are not the same length");
    }
    List<String> n = names.stream().map(e -> 
    e.toUpperCase()).collect(Collectors.toList());
    surnames.stream().map(e -> n.add(e)).collect(Collectors.toList());
    return n;
    }

List<String> fname = List.of("A", "B", "C", "D", "E", "F");
List<String> lname = List.of("G", "H", "I", "J", "K", "L");

the output : [A, B, C, D, E, F, G, H, I, J, K, L]

Answer

I assume you don’t need a specific order in the result list of names and surnames. I would recommend to remove use of streams:

static List<String> ex2(List<String> names, List<String> surnames) {
    if (names.size() != surnames.size()) {
        throw new IllegalArgumentException("the two lists are not the same length");
    }
    List<String> namesAndSurnames = new ArrayList<>(names);
    namesAndSurnames.addAll(surnames);
    return namesAndSurnames;
}


Source: stackoverflow