Java에서 배열을 목록으로 변환
Java에서 배열을 목록으로 어떻게 변환합니까?
나는 Arrays.asList()
그러나 동작 (및 서명)을 어떻게 든 Java SE 1.4.2 (아카이브에있는 문서)에서 8 로 변경했으며 웹에서 찾은 대부분의 조각은 1.4.2 동작을 사용합니다.
예를 들면 :
int[] spam = new int[] { 1, 2, 3 };
Arrays.asList(spam)
- 1.4.2에서 1, 2, 3 요소가 포함 된 목록을 반환합니다.
- 1.5.0 이상에서는 배열 스팸이 포함 된 목록을 반환합니다.
대부분의 경우 쉽게 감지 할 수 있지만 때로는 눈에 띄지 않게 미끄러질 수 있습니다.
Assert.assertTrue(Arrays.asList(spam).indexOf(4) == -1);
귀하의 예에서는 기본 유형의 목록을 가질 수 없기 때문입니다. 즉, List<int>
불가능합니다.
그러나 프리미티브 를 래핑하는 클래스를 List<Integer>
사용할 수 있습니다 . A에 대한 배열을 변환 와 유틸리티 메소드.Integer
int
List
Arrays.asList
Integer[] spam = new Integer[] { 1, 2, 3 };
List<Integer> list = Arrays.asList(spam);
이 코드는 IdeOne.com에서 실시간으로 실행 됩니다.
Java 8에서는 스트림을 사용할 수 있습니다.
int[] spam = new int[] { 1, 2, 3 };
Arrays.stream(spam)
.boxed()
.collect(Collectors.toList());
변환 방법에 대해 말하면 왜 List
. 데이터를 읽는 데 필요한 경우. 좋습니다. 여기 있습니다.
Integer[] values = { 1, 3, 7 };
List<Integer> list = Arrays.asList(values);
하지만 다음과 같이하면 :
list.add(1);
당신은 얻는다 java.lang.UnsupportedOperationException
. 따라서 어떤 경우에는 이것이 필요합니다.
Integer[] values = { 1, 3, 7 };
List<Integer> list = new ArrayList<Integer>(Arrays.asList(values));
첫 번째 접근 방식은 실제로 배열을 변환하지 않지만 List
. 그러나 배열은 고정 된 수의 요소와 같은 모든 속성을 가지고 있습니다. 을 생성 할 때 유형을 지정해야합니다 ArrayList
.
문제는 varargs가 Java5에 도입되었고 불행히도 Arrays.asList()
vararg 버전에서도 과부하가 발생 했다는 것 입니다. 따라서 Arrays.asList(spam)
Java5 컴파일러는 int 배열의 vararg 매개 변수로 이해합니다.
이 문제는 Effective Java 2nd Ed., Chapter 7, Item 42에 자세히 설명되어 있습니다.
조금 늦은 것 같지만 여기 내 2 센트가 있습니다. 원시 유형 을 List<int>
그대로 가질 수 없으므로 .int
List<Integer>
Java 8 (int 배열)
int[] ints = new int[] {1,2,3,4,5};
List<Integer> list11 =Arrays.stream(ints).boxed().collect(Collectors.toList());
Java 8 이하 (정수 배열)
Integer[] integers = new Integer[] {1,2,3,4,5};
List<Integer> list21 = Arrays.asList(integers); // returns a fixed-size list backed by the specified array.
List<Integer> list22 = new ArrayList<>(Arrays.asList(integers)); // good
List<Integer> list23 = Arrays.stream(integers).collect(Collectors.toList()); //Java 8 only
List가 아닌 ArrayList가 필요하십니까?
List
예 ArrayList
를 들어 특정 구현을 원하는 경우 다음 toCollection
과 같이 사용할 수 있습니다 .
ArrayList<Integer> list24 = Arrays.stream(integers)
.collect(Collectors.toCollection(ArrayList::new));
list21
구조적으로 수정할 수없는 이유 는 무엇 입니까?
우리가 사용할 때 Arrays.asList
반환 된 목록의 크기는 고정 된 목록이 java.util.ArrayList
아니라 내부에 정의 된 개인 정적 클래스 이기 때문 java.util.Arrays
입니다. 따라서 반환 된 목록에서 요소를 추가하거나 제거 UnsupportedOperationException
하면이 발생합니다. 따라서 list22
목록을 수정하고 싶을 때 함께 가야 합니다. Java8이 있으면 list23
.
명확하게하려면 list21
우리가 호출 할 수 있다는 의미에서 수정할 수 list21.set(index,element)
있지만이 목록은 구조적으로 수정할 수 없습니다. 즉, 목록에서 요소를 추가하거나 제거 할 수 없습니다. 이 질문을 확인할 수도 있습니다 .
불변 목록을 원하면 다음과 같이 래핑 할 수 있습니다.
List<Integer> list 22 = Collections.unmodifiableList(Arrays.asList(integers));
Another point to note is that the method Collections.unmodifiableList
returns an unmodifiable view of the specified list. An unmodifiable view collection is a collection that is unmodifiable and is also a view onto a backing collection. Note that changes to the backing collection might still be possible, and if they occur, they are visible through the unmodifiable view.
We can have a truly immutable list in Java 10.
Java 10 (Truly Immutable list) in two ways:
List.copyOf(Arrays.asList(integers))
Arrays.stream(integers).collect(Collectors.toUnmodifiableList());
Also check this answer of mine for more.
I recently had to convert an array to a List. Later on the program filtered the list attempting to remove the data. When you use the Arrays.asList(array) function, you create a fixed size collection: you can neither add nor delete. This entry explains the problem better than I can: Why do I get an UnsupportedOperationException when trying to remove an element from a List?.
In the end, I had to do a "manual" conversion:
List<ListItem> items = new ArrayList<ListItem>();
for (ListItem item: itemsArray) {
items.add(item);
}
I suppose I could have added conversion from an array to a list using an List.addAll(items) operation.
Even shorter:
List<Integer> list = Arrays.asList(1, 2, 3, 4);
Using Arrays
This is the simplest way to convert an array to List
. However, if you try to add a new element or remove an existing element from the list, an UnsupportedOperationException
will be thrown.
Integer[] existingArray = {1, 2, 3};
List<Integer> list1 = Arrays.asList(existingArray);
List<Integer> list2 = Arrays.asList(1, 2, 3);
// WARNING:
list2.add(1); // Unsupported operation!
list2.remove(1); // Unsupported operation!
Using ArrayList or Other List Implementations
You can use a for
loop to add all the elements of the array into a List
implementation, e.g. ArrayList
:
List<Integer> list = new ArrayList<>();
for (int i : new int[]{1, 2, 3}) {
list.add(i);
}
Using Stream API in Java 8
You can turn the array into a stream, then collect the stream using different collectors: The default collector in Java 8 use ArrayList
behind the screen, but you can also impose your preferred implementation.
List<Integer> list1, list2, list3;
list1 = Stream.of(1, 2, 3).collect(Collectors.toList());
list2 = Stream.of(1, 2, 3).collect(Collectors.toCollection(ArrayList::new));
list3 = Stream.of(1, 2, 3).collect(Collectors.toCollection(LinkedList::new));
See also:
Another workaround if you use apache commons-lang:
int[] spam = new int[] { 1, 2, 3 };
Arrays.asList(ArrayUtils.toObject(spam));
Where ArrayUtils.toObject converts int[]
to Integer[]
In Java 9 you have the even more elegant solution of using immutable lists via the new convenience factory method List.of
:
List<String> immutableList = List.of("one","two","three");
(shamelessly copied from here )
If you are targeting Java 8 (or later), you can try this:
int[] numbers = new int[] {1, 2, 3, 4};
List<Integer> integers = Arrays.stream(numbers)
.boxed().collect(Collectors.<Integer>toList());
NOTE:
Pay attention to the Collectors.<Integer>toList()
, this generic method helps you to avoid the error "Type mismatch: cannot convert from List<Object>
to List<Integer>
".
you have to cast in to array
Arrays.asList((Object[]) array)
One-liner:
List<Integer> list = Arrays.asList(new Integer[] {1, 2, 3, 4});
Using Guava:
Integer[] array = { 1, 2, 3}; List<Integer> list = Lists.newArrayList(sourceArray);
Using Apache Commons Collections:
Integer[] array = { 1, 2, 3}; List<Integer> list = new ArrayList<>(6); CollectionUtils.addAll(list, array);
So it depends on which Java version you are trying-
Java 7
Arrays.asList(1, 2, 3);
OR
final String arr[] = new String[] { "G", "E", "E", "K" };
final List<String> initialList = new ArrayList<String>() {{
add("C");
add("O");
add("D");
add("I");
add("N");
}};
// Elements of the array are appended at the end
Collections.addAll(initialList, arr);
OR
Integer[] arr = new Integer[] { 1, 2, 3 };
Arrays.asList(arr);
In Java 8
int[] num = new int[] {1, 2, 3};
List<Integer> list = Arrays.stream(num)
.boxed().collect(Collectors.<Integer>toList())
Reference - http://www.codingeek.com/java/how-to-convert-array-to-list-in-java/
If this helps: I've had the same problem and simply wrote a generic function that takes an array and returns an ArrayList of the same type with the same contents:
public static <T> ArrayList<T> ArrayToArrayList(T[] array) {
ArrayList<T> list = new ArrayList<T>();
for(T elmt : array) list.add(elmt);
return list;
}
Given Array:
int[] givenArray = {2,2,3,3,4,5};
Converting integer array to Integer List
One way: boxed() -> returns the IntStream
List<Integer> givenIntArray1 = Arrays.stream(givenArray)
.boxed()
.collect(Collectors.toList());
Second Way: map each element of the stream to Integer and then collect
NOTE: Using mapToObj you can covert each int element into string stream, char stream etc by casing i to (char)i
List<Integer> givenIntArray2 = Arrays.stream(givenArray)
.mapToObj(i->i)
.collect(Collectors.toList());
Converting One array Type to Another Type Example:
List<Character> givenIntArray2 = Arrays.stream(givenArray)
.mapToObj(i->(char)i)
.collect(Collectors.toList());
use two line of code to convert array to list if you use it in integer value you must use autoboxing type for primitive data type
Integer [] arr={1,2};
Arrays.asList(arr);
참고URL : https://stackoverflow.com/questions/2607289/converting-array-to-list-in-java
'program tip' 카테고리의 다른 글
extern을 사용하여 소스 파일간에 변수를 공유하려면 어떻게해야합니까? (0) | 2020.09.28 |
---|---|
Git : 마스터에서 준비되지 않은 / 커밋되지 않은 변경 사항에서 분기 만들기 (0) | 2020.09.28 |
Docker 컨테이너의 셸에 어떻게 들어가나요? (0) | 2020.09.28 |
jQuery 데이터 속성 값을 기반으로 요소를 찾는 방법은 무엇입니까? (0) | 2020.09.28 |
원격에서 더 이상 추적 분기 제거 (0) | 2020.09.28 |