Java 데이터 다루기 입문

### 들어가기전
- 소스 : https://github.com/ohhoonim/collections-java.git
- 컬렉션, 함수형프로그래밍, 스트림 
## 컬렉션
- 컬렉션이란?
	- '컬렉션' === '데이터집합'
	- 전공자들이 배우는 자료구조와는 살짝 다른 것 임
	- 수학에서 배우는 집합과는 조금 다른게 교집합, 합집합 이런 건 없음.
-  컬렉션을 객체로 볼까 말까
	- 컬렉션을 단순히 여러 객체를 한번에 가리키는 역할로만 볼 수도 있지만 컬렉션 자체를 객체로 볼 수도 있다. 
	- 컬렉션을 객체로 취급하면 매개변수 전달시 참조 호출의 효과를 얻을 수 있다. 참조 호출이므로 컬렉션 내의 값을 변경하면 컬렉션이 변경될 수 있다. 
-  컬렉션과 제네릭
	- 다양한 형태의 데이터집합을 다루려면 매번 데이터집합 타입에 맞는 컬렉션 클래스를 작성할 순 없다.
	- 예제코드 : [CollectionIsObject.java]
- 어떤 컬렉션을 쓸가
	- Collection vs Iterable vs List ??
	- 컬렉션이 표현하는 개념
		- 크기
		- 원소간 순서
		- 원소의 독자성 
	- 켈렉션을 선택했다는 것은 개발자의 성능에 대한 의도를 드러낸다
## 컬렉션 인터페이스와 구현체
- 예제코드 : [CollectionInterfaces.java]
- 배열 : 크기 고정. 가장 단순한 형태
- Iterable : 순차 열람을 지원하는 컬렉션
- Collection : 원소 추가, 제거 기능
	- ArrayList : 기본 구현체이다.
- List : 원소의 순서가 있으며, 위치 정보(index)를 통해 접근 가능
	- ArrayList : 원소 검색시 장점이 있다 
	- LinkedList : 원소 수정시 장점이 있다.
- Set : 중복된 원소가 없는 컬렉션
	- HashSet : 빠르지만 순서는 보장하지 않는다
	- LinkedHashSet : 순서를 보장하지만 조금 느리다
	- TreeSet : 원소를 정렬해주지만 수정시 logN에 비례한다.
- SortedSet : 중복 원소가 없으면서 원소간 순서가 정해진 컬렉션
- Map : 키(key)에 의해 원소에 접근
	- HashMap: 빠르지만 순서는 보장하지 않는다
	- LinkedHashMap : 원소간 순서를 보장한다
	- TreeMap : 키에 따라 순차열람이 가능하지만 수정시 logN에 비례한다.
- 유틸 클래스 :  Collections
	- 예제코드 : [CollectionUtil.java]
## 스트림 들어가기전 함수형 프로그래밍
-  컬렉션과 스트림
	- Stream은 Collection을 대체하려고 만든 것이 아니다. 
	- 조합해서 잘 쓰면 된다.
- 다섯 형태만 기억하자 
	- consumer : input만 있는 형태
	- supplier : output만 있는 형태
	- function : input/output이 모두 있는 형태
	- predict : 참/거짓을 판별하는 형태
	- runner : input/output 이 없는 형태
- 예제코드 : [Functional.java]
## 스트림 연산과 파이프라인
- intermediate operation : return a new stream. They are always _lazy_;
	- stateless : filter, map, flatMap, peek
	- stateful  :  distinct, sorted, skip, dropWhile
		- short-circuiting, limit, takeWhile
- terminal operation
	- forEach, forEachOrdered, toArray, reduce, collect, toList, min, max, count
	- short-circuiting : anyMatch, allMatch, noneMatchj, findFirst, findAny
```java
int sum = widgets.stream()
                      .filter(w -> w.getColor() == RED)
                      .mapToInt(w -> w.getWeight())
                      .sum();
```
## 스트림 필수 유틸 클래스 : Collectors
```java
 // Accumulate names into a List
 List<String> list = people.stream()
   .map(Person::getName)
   .collect(Collectors.toList());

 // Accumulate names into a TreeSet
 Set<String> set = people.stream()
   .map(Person::getName)
   .collect(Collectors.toCollection(TreeSet::new));

 // Convert elements to strings and concatenate them, separated by commas
 String joined = things.stream()
   .map(Object::toString)
   .collect(Collectors.joining(", "));

 // Compute sum of salaries of employee
 int total = employees.stream()
   .collect(Collectors.summingInt(Employee::getSalary));

 // Group employees by department
 Map<Department, List<Employee>> byDept = employees.stream()
   .collect(Collectors.groupingBy(Employee::getDepartment));

 // Compute sum of salaries by department
 Map<Department, Integer> totalByDept = employees.stream()
   .collect(Collectors.groupingBy(Employee::getDepartment,                                  Collectors.summingInt(Employee::getSalary)));

 // Partition students into passing and failing
 Map<Boolean, List<Student>> passingFailing = students.stream()
   .collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD));

```

댓글

이 블로그의 인기 게시물

Session 대신 JWT를 사용하는 이유

VSCode에서의 VIM 단축키와 키보드 구매 가이드

우분투에서 테스트링크(testlink)와 맨티스(mantis)로 테스팅 서버 구성하기