List -> Array(배열)
1) for문 사용
for문 방식은 arrayList (리스트) 데이터를 for문을 통해 순서데로 String 배열에 넣는다
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Test1");
arrayList.add("Test2");
arrayList.add("Test3");
String[] array = new String[arrayList.size()];
int size=0;
for(String temp : arrayList){
array[size++] = temp;
}
2) arrayList.toArray
- List에서 제공하는 메서드
- ArrayList.toArray() 의 경우, Object array를 리턴하여 타입 캐스팅을 해서 사용을 해야 하는 번거로움이 있다.
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add(new Integer(1));
Object[] arr = arrayList.toArray();
int sum = 0;
for(int i =0; i<arr.length; i++){
sum += ((Integer) arr[i]).intValue();
3) stream API (자바 8이상)
int arr = {};
ArrayList<String> list = new ArrayList<>();
list.add("Test1");
list.add("Test2");
list.add("Test3");
//1
arr = list.stream().mapToInt(i->i).toArray();
//2
arr = lsit.stream().mapToInt(Integer::intValue).toArrary();
- Integer::intValue : ::를 기준으로 왼쪽 객체의 오른쪽 메소드를 사용한다.
ex)
list.stream()
.filter(val -> Objects.equals(val, "A")
.map(String::toLowerCase)
.collect(Collectors.toList())
);
'java' 카테고리의 다른 글
int to char (정수형 데이터를 char형으로 변환) (0) | 2023.06.12 |
---|---|
parseInt() / intValue() (0) | 2023.06.01 |
정규표현식 (0) | 2023.02.26 |
Collection(Set) (0) | 2022.10.12 |
Properties (0) | 2022.10.12 |