티스토리 뷰
● 도입
- Stream 안에 있는 데이터를 변형하는데 사용하는 method
- 데이터에 해당 함수가 적용된 결과물을 제공하는 stream을 return
[Stream interface에 있는 map method]
public interface Stream<T> extends BaseStream<T, Stream<T>> {
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
}
- T type 데이터를 받아서 해당 데이터를 변형한 후 R type 데이터로 return한다.
● 실습
1. 숫자를 2배로 만들자
package com.fastcampus.functionalprogramming.chapter6;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.fastcampus.functionalprogramming.chapter6.model.Order;
import com.fastcampus.functionalprogramming.chapter6.model.Order.OrderStatus;
import com.fastcampus.functionalprogramming.chapter6.model.User;
public class Chapter6Section3 {
public static void main(String[] args) {
Function<Integer, Integer> doubleFunc = (Integer x) -> {
return x * 2;
};
List<Integer> numberList = Arrays.asList(-4, 3, 6);
// 1.
// x2가 되게 해보자
Stream<Integer> numberStream = numberList.stream();
Stream<Integer> numberStream2 = numberStream.map(doubleFunc);
// 간단 : Stream<Integer> numberStream2 = numberStream.map(x -> x * 2);
List<Integer> numberListX2 = numberStream2.collect(Collectors.toList());
System.out.println(numberListX2);
// 1-1.
// x3이 되게 해보자
List<Integer> numberListX3 = numberList.stream().map(x -> x * 3).collect(Collectors.toList());
System.out.println(numberListX3);
// 2.
// output 타입을 다르게(input : Integer / output : String)
Stream<Integer> numberListStream = numberList.stream();
Stream<String> strStream = numberListStream.map(x -> "Number is " + x);
List<String> strList = strStream.collect(Collectors.toList());
System.out.println(strList);
}
}
2.
2-1. user object가 담긴 List를 이용해 user의 이메일만 담겨있는 List를 만들자
package com.fastcampus.functionalprogramming.chapter6.model;
import java.util.List;
public class User {
private int id;
private String name;
private String emailAddress;
private boolean isVerified;
private List<Integer> friendUserIds;
public int getId() {
return id;
}
public User setId(int id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public User setName(String name) {
this.name = name;
return this;
}
public String getEmailAddress() {
return emailAddress;
}
public User setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
return this;
}
public boolean isVerified() {
return isVerified;
}
public User setVerified(boolean isVerified) {
this.isVerified = isVerified;
return this;
}
public List<Integer> getFriendUserIds() {
return friendUserIds;
}
public User setFriendUserIds(List<Integer> friendUserIds) {
this.friendUserIds = friendUserIds;
return this;
}
@Override
public String toString() {
return "User [id=" + id + ", " + (name != null ? "name=" + name + ", " : "")
+ (emailAddress != null ? "emailAddress=" + emailAddress + ", " : "") + "isVerified=" + isVerified
+ ", " + (friendUserIds != null ? "friendUserIds=" + friendUserIds : "") + "]";
}
}
package com.fastcampus.functionalprogramming.chapter6;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.fastcampus.functionalprogramming.chapter6.model.Order;
import com.fastcampus.functionalprogramming.chapter6.model.Order.OrderStatus;
import com.fastcampus.functionalprogramming.chapter6.model.User;
public class Chapter6Section3 {
public static void main(String[] args) {
// User object가 담긴 List를 이용해 user의 이메일만 담겨있는 List를 만들자
User user1 = new User();
user1.setId(101);
user1.setName("Alice");
user1.setVerified(true);
user1.setEmailAddress("Alice@garden.com");
User user2 = new User();
user2.setId(102);
user2.setName("Bob");
user2.setVerified(false);
user2.setEmailAddress("Bob@garden.com");
User user3 = new User();
user3.setId(103);
user3.setName("Charlie");
user3.setVerified(true);
user3.setEmailAddress("Charlie@garden.com");
List<User> users = Arrays.asList(user1, user2, user3);
List<String> emailAddresses = users.stream().map(User::getEmailAddress).collect(Collectors.toList());
// User::getEmailAddress --> Method Reference : 각 object 마다 object 안에 있는 instance method 적용
// 다른 방법 : List<String> emailAddresses = users.stream().map(user -> user.getEmailAddress()).collect(Collectors.toList());
System.out.println(emailAddresses);
}
}
2-2. Order object가 담긴 List를 이용해 createdByUserId 만 모여있는 List를 만들자
package com.fastcampus.functionalprogramming.chapter6.model;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
public class Order {
private long id;
private LocalDateTime createdAt;
private long createdByUserId;
private OrderStatus status;
private BigDecimal amount;
private List<OrderLine> orderLines;
public enum OrderStatus {
CREATED,
IN_PROGRESS,
ERROR,
PROCESSED
}
public long getId() {
return id;
}
public Order setId(long id) {
this.id = id;
return this;
}
public LocalDateTime getCreatedAt() {
return createdAt;
}
public Order setCreatedAt(LocalDateTime createdAt) {
this.createdAt = createdAt;
return this;
}
public long getCreatedByUserId() {
return createdByUserId;
}
public Order setCreatedByUserId(long createdByUserId) {
this.createdByUserId = createdByUserId;
return this;
}
public OrderStatus getStatus() {
return status;
}
public Order setStatus(OrderStatus status) {
this.status = status;
return this;
}
public BigDecimal getAmount() {
return amount;
}
public Order setAmount(BigDecimal amount) {
this.amount = amount;
return this;
}
public List<OrderLine> getOrderLines() {
return orderLines;
}
public Order setOrderLines(List<OrderLine> orderLines) {
this.orderLines = orderLines;
return this;
}
@Override
public String toString() {
return "Order [id=" + id + ", " + (createdAt != null ? "createdAt=" + createdAt + ", " : "")
+ "createdByUserId=" + createdByUserId + ", " + (status != null ? "status=" + status + ", " : "")
+ (amount != null ? "amount=" + amount + ", " : "")
+ (orderLines != null ? "orderLines=" + orderLines : "") + "]";
}
}
package com.fastcampus.functionalprogramming.chapter6;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.fastcampus.functionalprogramming.chapter6.model.Order;
import com.fastcampus.functionalprogramming.chapter6.model.Order.OrderStatus;
import com.fastcampus.functionalprogramming.chapter6.model.User;
public class Chapter6Section3 {
public static void main(String[] args) {
// Order object가 담긴 List를 이용해 createdByUserId 만 모여있는 List를 만들자
Order order1 = new Order();
order1.setId(1001);
order1.setStatus(OrderStatus.CREATED); // enum 사용
order1.setCreatedByUserId(101);
Order order2 = new Order();
order2.setId(1002);
order2.setStatus(OrderStatus.ERROR); // enum 사용
order2.setCreatedByUserId(103);
Order order3 = new Order();
order3.setId(1003);
order3.setStatus(OrderStatus.PROCESSED); // enum 사용
order3.setCreatedByUserId(102);
Order order4 = new Order();
order4.setId(1004);
order4.setStatus(OrderStatus.ERROR); // enum 사용
order4.setCreatedByUserId(104);
Order order5 = new Order();
order5.setId(1005);
order5.setStatus(OrderStatus.IN_PROGRESS); // enum 사용
order5.setCreatedByUserId(101);
List<Order> orders = Arrays.asList(order1, order2, order3, order4, order5);
List<Long> createdByUserIds = orders.stream().map(Order::getCreatedByUserId).collect(Collectors.toList());
System.out.println(createdByUserIds);
}
}
'Backend > Java8' 카테고리의 다른 글
#19 Stream - Sorted(데이터의 정렬) (0) | 2022.10.08 |
---|---|
#18 Stream - Stream의 구성 요소 (0) | 2022.10.07 |
#16 Stream - Filter (0) | 2022.10.05 |
#15 Stream이란? / Stream 만들어보기 (1) | 2022.10.04 |
#14 Method Reference를 이용해 기존 예제를 더 간단하게 (0) | 2022.10.03 |
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- java
- Advanced Stream
- Phaser
- DART
- 자료구조
- Spring Boot
- 운영체제
- MySQL
- 빅데이터
- 알고리즘
- API
- 빅데이터 분석기사
- 프로그래머스
- Stream
- OS
- 코테
- db
- Java8
- jpa
- spring
- 프로세스
- Phaser3
- git
- 코딩테스트
- 메모리
- SQL
- node.js
- SpringBoot
- MongoDB
- nosql
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
글 보관함