[JAVA]문법(배열, 리스트)

이건우·2023년 10월 14일
0

JAVA

목록 보기
3/5
post-thumbnail

List

List list = new ArrayList<>();

리스트의 길이

list.size();

요소삽입

list.add("one");

특정 인덱스에 요소 삽입

list.add(0,"zero");

특정 요소의 인덱스 반환

list.indexof("zero"); //첫번째 인덱스
list.lastindexof("zero); //마지막 인덱스

삭제

list.remove(0); //해당 인덱스 삭제
list.remove("one"); //해당 요소의 첫번째 값 삭제

리스트에 특정 요소 포함 체크

list.contain("one");
list.containsALL(list2); //다른 리스트의 요소가 전부 포함되었는지 체크

리스트 간의 연산

list.addAll(list2); //리스트 뒤에 다른 리스트 삽입
list.removeAll(list2); //리스트의 차집합
list.retainAll(list2); //리스트의 교집합

리스트가 비었는지 체크

list.isEmpty();

람다식 사용하여 요소 제거

list.removeIf(x -> x%2 == 0);

List와 Array의 형 변환

Array to List

String[] arr = {"a","b","c"};
List<String> list = new ArrayList<>(Arrays.asList(temp));

List to Array

List<String> list = new ArrayList<>();
String[] arr = list.toArray(new String[list.size()]);

Collections 관련 메소드

정수형 List 원소 중 최대, 최소값

Collections.max(list);
Collections.max(list);

List 정렬

Collections.sort(list); //오름차순(ASC)
Collections.sort(list, Collections.reverseOrder()); //내림차순(DESC)

List 뒤집기

Collections.reverse(list);

List 내 원소의 갯수 반환

  Collections.frequency(list,3);

List 내 원소를 이진탐색을 이용해 찾기(index 반환)

Collections.binarySearch(list, 10); //이진 탐색 이므로 오름차순 정렬 꼭 해야함.

탐색 대상이 없을 때는 (-(해당 탐색 대상이 있어야 하는 index)-1)이 반환된다.

profile
공부하고 발전하는 Backend 개발자

0개의 댓글