繁体   English   中英

断言这两个列表具有相同的长度。 创建所有姓名和姓氏的列表

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

  1. 断言这两个列表具有相同的长度。 完毕
  2. 创建所有姓名和姓氏的列表。 完毕
  3. 有没有更好的方法来做到这一点? 还是可以减少代码? ---> 我需要帮助。
    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");

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

您可以使用Stream.concat()Stream.sorted()函数。 例如:

    public static void main(String[] args) {
        List<String> fname = List.of("A", "B", "C", "D", "E", "F");
        List<String> lname = List.of("G", "H", "I", "J", "K", "L");
        List<String> together = Stream.concat(fname.stream(), lname.stream()).sorted().collect(Collectors.toList());
        System.out.println(together);
    }

我假设您不需要姓名和姓氏结果列表中的特定顺序。 我建议删除流的使用:

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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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