Java/컬렉션

[Java]ArrayList 여러 값 추가하는 방법

DevStory 2022. 9. 16.

ArrayList 여러 값 추가하는 방법

ArrayList에 여러 개의 값을 추가해야 하는 경우가 존재할 수 있습니다.

 

예를 들어, 배열로 선언된 변수를 ArrayList에 추가하거나 다른 ArrayList를 추가해야 하는 상황이 존재합니다.

 

이번 포스팅은 ArrayList에 여러 값을 추가할 수 있는 몇 가지 방법을 소개합니다.


방법 1. ArrayList 초기화

ArrayList 선언과 동시에 여러 값을 추가해야 하는 경우 ArrayList 생성자 함수에 Arrays 클래스의 asList() 메서드를 사용합니다.

 

다음 예제는 ArrayList 선언과 동시에 Arrays 클래스의 asList() 메서드를 사용하여 여러 값을 추가하는 몇 가지 방법을 보여줍니다.

public static void main(String args[]) {
  String[] strArray = {"One", "Two", "Three"};

  // 방법 1. 값을 직접 입력하여 전달
  ArrayList<String> strArrayList1 =
          new ArrayList<>(Arrays.asList("One", "Two", "Three"));

  // 방법 2. 배열로 선언된 변수를 전달
  ArrayList<String> strArrayList2 =
          new ArrayList<>(Arrays.asList(strArray));

  // 방법 3. ArrayList 객체를 전달(Arrays.asList() 사용 안함)
  ArrayList<String> strArrayList3 =
          new ArrayList<>(strArrayList1);

  System.out.println("strArrayList1: " + strArrayList1);
  System.out.println("strArrayList2: " + strArrayList2);
  System.out.println("strArrayList3: " + strArrayList3);
}

[실행 결과]

strArrayList1: [One, Two, Three]
strArrayList2: [One, Two, Three]
strArrayList3: [One, Two, Three]

방법 2. ArrayList 클래스의 addAll 메서드(권장)

또 다른 방법으로 ArrayList 클래스의 addAll() 메서드를 사용하여 여러 값을 추가할 수 있습니다.

 

addAll() 메서드는 오버로드된 두 개의 버전이 존재하며, 값이 정상적으로 추가되면 true를 반환하고 그렇지 않으면 false를 반환합니다.

public boolean addAll(Collection<? extends E> c);
public boolean addAll(int index, Collection<? extends E> c);

첫 번째 addAll() 메서드는 매개변수로 전달된 값을 ArrayList 마지막 위치에 추가합니다.

 

두 번째 addAll() 메서드는 값이 추가되는 위치(index)를 전달하여 여러 값을 추가할 수 있습니다.

 

다음 예제는 첫 번째 addAll() 메서드를 사용하여 ArrayList에 여러 값을 추가합니다.

public static void main(String args[]) {
  String[] strArray = {"Four", "Five", "Six"};
  boolean isAddall = false;

  ArrayList<String> strArrayList =
          new ArrayList<>(Arrays.asList("One", "Two", "Three"));

  System.out.println("추가 전: " + strArrayList);

  isAddall = strArrayList.addAll(Arrays.asList(strArray));

  System.out.println("추가 후: " + strArrayList);
  System.out.println("addAll() 메서드 실행 결과: " + isAddall);
}

[실행 결과]

추가 전: [One, Two, Three]
추가 후: [One, Two, Three, Four, Five, Six]
addAll() 메서드 실행 결과: true

배열은 Collection 형식이 아니므로 Arrays.asList() 메서드를 사용하여 Colletion 형식으로 변환된 값을 매개변수로 전달합니다. 실행 결과에서 확인할 수 있듯이 ArrayList 마지막 위치에 여러 값이 추가됩니다.

 

다음 예제는 두 번째 addAll() 메서드를 사용하여 ArrayList의 1번째 인덱스부터 여러 값을 추가합니다.

public static void main(String args[]) {
  String[] strArray = {"Two", "Three", "Four"};
  boolean isAddall = false;

  ArrayList<String> strArrayList =
          new ArrayList<>(Arrays.asList("One", "Five", "Six"));

  System.out.println("추가 전: " + strArrayList);

  isAddall = strArrayList.addAll(1, Arrays.asList(strArray));

  System.out.println("추가 후: " + strArrayList);
  System.out.println("addAll() 메서드 실행 결과: " + isAddall);
}

[실행 결과]

추가 전: [One, Five, Six]
추가 후: [One, Five, Two, Three, Four, Six]
addAll() 메서드 실행 결과: true

방법 3. Collections 클래스의 addAll 메서드

세 번째 방법으로 Collections 클래스의 addAll() 메서드를 사용하여 여러 값을 추가할 수 있습니다.

public static <T> boolean addAll(Collection<? super T> c, T... elements);

첫 번째 매개변수에 ArrayList 객체를 전달하고 두 번째 매개변수부터 추가하려는 값을 전달합니다. 값이 정상적으로 추가되면 true를 반환하고 그렇지 않으면 false를 반환합니다.

 

이 방법의 단점은 여러 값이 추가되는 위치를 설정할 수 없다는 것입니다.

 

다음 예제는 Collections 클래스의 addAll() 메서드를 사용하여 배열을 ArrayList에 추가합니다.

public static void main(String args[]) {
  String[] strArray = {"Four", "Five", "Six"};
  boolean isAddall = false;

  ArrayList<String> strArrayList =
          new ArrayList<>(Arrays.asList("One", "Two", "Three"));

  System.out.println("추가 전: " + strArrayList);

  isAddall = Collections.addAll(strArrayList, strArray);

  System.out.println("추가 후: " + strArrayList);
  System.out.println("addAll() 메서드 실행 결과: " + isAddall);
}

[실행 결과]

추가 전: [One, Two, Three]
추가 후: [One, Two, Three, Four, Five, Six]
addAll() 메서드 실행 결과: true

 

다음 예제는 Collections 클래스의 addAll() 메서드에 배열이 아닌 여러 개의 매개변수를 전달합니다.

public static void main(String args[]) {
  boolean isAddall = false;

  ArrayList<String> strArrayList =
          new ArrayList<>(Arrays.asList("One", "Two", "Three"));

  System.out.println("추가 전: " + strArrayList);

  isAddall = Collections.addAll(strArrayList, "Four", "Five", "Six", "Seven");

  System.out.println("추가 후: " + strArrayList);
  System.out.println("addAll() 메서드 실행 결과: " + isAddall);
}

[실행 결과]

추가 전: [One, Two, Three]
추가 후: [One, Two, Three, Four, Five, Six, Seven]
addAll() 메서드 실행 결과: true

방법 4. Stream API

마지막 방법으로 Java의 버전이 1.8 이상인 경우 Stream API를 사용하여 ArrayList에 여러 개의 값을 추가할 수 있습니다.

 

Stream에 대한 이해가 없으면, 다소 어려울 수 있으나 이 방법의 장점은 값을 추가할 때, 조건식을 지정할 수 있다는 것입니다.

 

다음 예제는 ArrayList를 스트림으로 변환 후 forEachOrdered() 메서드를 호출하여 다른 ArrayList의 요소를 추가합니다.

public static void main(String args[]) {
  ArrayList<String> sourceArrayList =
          new ArrayList<>(Arrays.asList("One", "Two", "Three"));

  ArrayList<String> destArrayList =
          new ArrayList<>(Arrays.asList("Four", "Five", "Six", "Six", "Six"));

  System.out.println("추가 전: " + sourceArrayList);

  destArrayList.stream()
        .forEachOrdered(sourceArrayList::add);

  System.out.println("추가 후: " + sourceArrayList);
}

[실행 결과]

추가 전: [One, Two, Three]
추가 후: [One, Two, Three, Four, Five, Six, Six, Six]

 

다음 예제는 ArrayList를 스트림으로 변환 후 distinct() 메서드를 호출하여 중복 값 제거 후 forEachOrdered() 메서드를 호출합니다.

public static void main(String args[]) {
  ArrayList<String> sourceArrayList =
          new ArrayList<>(Arrays.asList("One", "Two", "Three"));

  ArrayList<String> destArrayList =
          new ArrayList<>(Arrays.asList("Four", "Five", "Six", "Six", "Six"));

  System.out.println("추가 전: " + sourceArrayList);

  destArrayList.stream()
          .distinct()
          .forEachOrdered(sourceArrayList::add);

  System.out.println("추가 후: " + sourceArrayList);
}

[실행 결과]

추가 전: [One, Two, Three]
추가 후: [One, Two, Three, Four, Five, Six]

 

다음 예제는 ArrayList를 스트림으로 변환 후 filter() 메서드를 호출하여 10보다 작은 요소만 추출한 뒤 forEachOrdered() 메서드를 호출합니다.

public static void main(String args[]) {
  ArrayList<Integer> sourceArrayList =
          new ArrayList<>(Arrays.asList(1, 2, 3));

  ArrayList<Integer> destArrayList =
          new ArrayList<>(Arrays.asList(4, 5, 6, 10, 20, 30));

  System.out.println("추가 전: " + sourceArrayList);

  destArrayList.stream()
          .filter(num -> num < 10)
          .forEachOrdered(sourceArrayList::add);

  System.out.println("추가 후: " + sourceArrayList);
}

[실행 결과]

추가 전: [1, 2, 3]
추가 후: [1, 2, 3, 4, 5, 6]
반응형

댓글