티스토리 뷰
여러 데이터의 묶음을 컬렉션이라고 한다.
- Collection
- List
- LinkedList
- ArrayList
- Set
- HashSet
- SortedSet
- TreeSet
- List
Map은 Collection Interface에 포함되지 않는다.
- Map
- Hashtable
- HashMap
- LinkedHashMap
- SortedMap
- TreeMap
메소드 체이닝 예제
//MyCollection.java
public class MyCollection<T> {
private List<T> list;
public MyCollection(List<T> list) {
this.list = list;
}
public <U> MyCollection<U> map(Function<T, U> function) { // T타입으로부터 U타입을 만드는 function을 인자로 받는다.
// 이 메소드에서만 사용할 U 타입을 정의한다.
// MyCollection<U>가 반환형이고, T와 U를 변수로 받는 function이 매개변수이다.
List<U> newList = new ArrayList<>();
foreach(d -> newList.add(function.apply(d)));
return new MyCollection<>(newList);
}
public MyCollection<T> filter(Predicate<T> predicate) {
List<T> new List = new ArrayList<>();
foreach(d -> {
if (predicate.test(d)) new List.add(d);
});
return new MyCollection<>(newList);
}
public void foreach(Consumer<T> consumer) {
for (int i = 0; i < list.size(); i++) {
T data = list.get(i);
consumer.accept(data);
}
}
public int count() {
return list.size();
}
}
//Main.java
public class Main {
public static void main(String[] args) {
MyCollection<String> c1 = new MyCollection<>(Arrays.asList("A", "AB", "ABC", "ABCD", "ABCDEE"));
MyCollection<Integer> c2 = c1.map(String::length);
MyCollection<Integer> c3 = c2.filter(i -> i % 2 == 0);
c3.foreach(System.out::println);
//-----------------------------
// 위와 아래의 코드는 동일하다.
new MyCollection<>(Arrays.asList(("A", "AB", "ABC", "ABCD", "ABCDEE"))
.map(String::length)
.filter(i -> i % 2 == 0)
.foreach(System.out::println);
}
}
728x90
반응형
'프로그래머스 백엔드 1기 > Java' 카테고리의 다른 글
Java Collection (3) - Optional (0) | 2021.08.08 |
---|---|
Java Collection (2) - Iterator, Stream (0) | 2021.08.08 |
Java Interface (6) - 제네릭을 이용한 Consumer, Predicate 패턴 (0) | 2021.08.08 |
Java Interface (5) - 메소드 레퍼런스 (0) | 2021.08.08 |
Java Interface (4) - 람다 표현식 (익명 메소드) (0) | 2021.08.08 |
댓글