如何将 ArrayList 的每个元素重复 n 次?

-1 java java-8

我必须将 ArrayList 的每个元素复制 n 次。我试图通过以下方式做到这一点:

List<String> elements = new ArrayList();
elements.add("1");
elements.add("2");
elements.add("3");
List<String> newList = new ArrayList();
for(int i = 0; i < elements.size(); i++){
        newList = Collections
                .nCopies(10, elements.get(i));
    }
Run Code Online (Sandbox Code Playgroud)

但它只重复元素 List 的最后一个元素 10 次

azr*_*zro 5

newList =每次都重新分配,你添加到同一个。你需要使用addAll

  • 不要使用原始泛型, new ArrayList() --> new ArrayList<>()
  • 你可以使用 foreach 循环 for (String element : elements)
List<String> elements = Arrays.asList("1", "2", "3")
List<String> newList  = new ArrayList<>();
for (String element : elements) {
    newList.addAll(Collections.nCopies(10, element));
}

// [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3]
Run Code Online (Sandbox Code Playgroud)

使用Stream它看起来像

List<String> newList = elements.stream()
                               .map(elt -> Collections.nCopies(10, elt))
                               .flatMap(List::stream)
                               .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)