Collection에 관련된 이야기들

어겐어갠·2022년 3월 24일
0

Collection이란?

  • 여러 데이터의 묶음
  • 추상체이며 이를 구상화한게 List, Set
    여기서 List는 ArrayList, LinkedList, Set은 HashSet, TreeSet으로 구현된다.
  • 메서드 체이닝

Iterator

  • 데이터의 묶음(Collection)을 풀어서 하나씩 접근한다.
  • next()를 통해 다음 데이터를 조회하고, hasNext()로 다음 데이터의 유무를 알수 있다.
  • 역방향 조회는 불가능하다

Stream

  • 데이터의 연속을 나타낸다.
  • 고차함수(함수를 인자로 받는 함수. filter, map, forEach, count, limit 등)
  • 효율적임

List를 Stream으로,
IntStream을 Stream으로,
Stream을 List로,
Stream을 Array로 (변환 형을 명시하지 않으면 Object가 된다)

		List<Integer> integers1 = Arrays.asList(1, 2, 3, 4);
		Stream<Integer> stream = Arrays.asList(1, 2, 3, 4).stream();
        IntStream stream1 = Arrays.stream(new int[]{1, 2, 3});
        Stream<Integer> boxed = Arrays.stream(new int[]{1, 2, 3}).boxed();
        List<Integer> collect = Arrays.stream(new int[]{1, 2, 3}).boxed().collect(Collectors.toList());
        Integer[] integers = Arrays.stream(new int[]{1, 2, 3}).boxed().toArray(Integer[]::new);

Stream을 만드는 방법

  1. generate
  2. iteator (초기값 지정)

Optional

  • Null Pointer Exception
  • 자바의 대부분은 null이 될 가능성 내포
  • 그러므로 매번 null인지 확인해야함

null을 안쓰려면?
1. EMPTY 객체를 만들어서 사용(기본값)
2. Optional 사용

Optional은 바구니
내용물 넣기 =of(내용물), empty(), ofNullable(null)
내용물 꺼내기 = .get(), .orElse()
확인방법 = isPresent(), isEmpty()
확인+조건문 = ifPresent(), ifPresentOrElse()

profile
음그래

0개의 댓글