티스토리 뷰

Backend/Java8

#31 Advanced Stream - Partitioning By

RadderNepa 2022. 10. 20. 01:59

● 도입

public static <T> Collector<T, ?, Map<Boolean, List<T>>> partitioningBy(Predicate<? super T> predicate)
(* 반환 타입 = Map<Boolean, List<T>>)

public static <T, D, A> Collector<T, ?, Map<Boolean, D>> partitioningBy(
            Predicate<? super T> predicate,
            Collector<? super T, A, D> downstream)
(* 반환 타입 = Map<Boolean, D>)

- GroupingBy와 유사
- Function 대신 Predicate을 받아 true와 false, 두 key가 존재하는 map을 반환하는 collector
- downstream collector를 넘겨 List 이외의 형태로 map의 value를 만드는 것도 가능하다.

- Partitioning By는 주어진 (조건을 만족하는 데이터 그룹)과 (그렇지 않은 데이터 그룹)으로 분리를 할 때 사용한다.

- 즉, Partitioning By의 결과값은 'true 그룹 / false 그룹 2개'로 나뉘는 것이다.

- 당연히 true와 false가 Map의 key가 되는 것이다.

 

 

● 실습

1.

package com.fastcampus.functionalprogramming.chapter8;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import com.fastcampus.functionalprogramming.chapter8.model.User;
import com.fastcampus.functionalprogramming.chapter8.service.EmailService;

public class Chapter8Section8 {
	public static void main(String[] args) {
		List<Integer> numbers = Arrays.asList(13, 2, 101, 203, 304, 402, 305, 349, 2312, 203);
		
		// 짝수, 홀수 그룹으로 나눠보자(짝수 = true, 홀수 = false)
		Map<Boolean, List<Integer>> numberPartitions = numbers.stream().collect(Collectors.partitioningBy(number -> number % 2 == 0));
		System.out.println(numberPartitions);
		System.out.println("짝수 : " + numberPartitions.get(true));
		System.out.println("홀수 : " + numberPartitions.get(false));
	}
}

 

2.

package com.fastcampus.functionalprogramming.chapter8.model;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

public class User {
	private int id;
	private String name;
	private String emailAddress;
	private boolean isVerified;
	private LocalDateTime createdAt;
	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 Optional<String> getEmailAddress() {
		return Optional.ofNullable(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 LocalDateTime getCreatedAt() {
		return createdAt;
	}
	
	public User setCreatedAt(LocalDateTime createdAt) {
		this.createdAt = createdAt;
		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.chapter8.service;

import java.util.Optional;

import com.fastcampus.functionalprogramming.chapter8.model.User;

public class EmailService {
	// 친구랑 놀아라
	public void sendPlayWithFriendsEmail(User user) {
		user.getEmailAddress().ifPresent(email -> 
			System.out.println("Sending 'Play With Friends' email to " + email));
	}
	// getEmailAddress method의 반환타입 = Optional<String>
	
	// 친구 좀 만들어
	public void sendMakeMoreFriendsEmail(User user) {
		user.getEmailAddress().ifPresent(email -> 
			System.out.println("Sending 'Make More Friends' email to " + email));
	}
	// getEmailAddress method의 반환타입 = Optional<String>
	
	public void sendVerifyYourEmailEmail(User user) {
		user.getEmailAddress().ifPresent(email -> 
			System.out.println("Sending 'Verify Your Email' email to " + email));
	}
	// getEmailAddress method의 반환타입 = Optional<String>
}
package com.fastcampus.functionalprogramming.chapter8;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import com.fastcampus.functionalprogramming.chapter8.model.User;
import com.fastcampus.functionalprogramming.chapter8.service.EmailService;

public class Chapter8Section8 {
	public static void main(String[] args) {
		User user1 = new User()
				.setId(101)
				.setName("Alice")
				.setEmailAddress("alice@fastcampus.co.kr")
				.setFriendUserIds(Arrays.asList(201, 202, 203, 204, 211, 212, 213, 214));
	    User user2 = new User()
	    		.setId(102)
	    		.setName("Bob")
	    		.setEmailAddress("bob@fastcampus.co.kr")
	    		.setFriendUserIds(Arrays.asList(204, 205, 206));
	    User user3 = new User()
	    		.setId(103)
	    		.setName("Charlie")
	    		.setEmailAddress("charlie@fastcampus.co.kr")
	    		.setFriendUserIds(Arrays.asList(204, 205, 207, 218));
	    
	    List<User> users = Arrays.asList(user1, user2, user3);
	    
	    /*
	     * TODO
	     * - user의 친구 숫자가 5명 초과 = "친구랑 놀아라"
	     * - user의 친구 숫자가 5명 이하 = "친구 좀 만들어"
	     * - 친구 숫자 = private List<Integer> friendUserIds
	     */
	    Map<Boolean, List<User>> userPartitions = users.stream().collect(Collectors.partitioningBy(user -> user.getFriendUserIds().size() > 5));
	    
	    EmailService emailService = new EmailService();
	    for (User user : userPartitions.get(true)) {
	    	emailService.sendPlayWithFriendsEmail(user);
		}
	    
	    for (User user : userPartitions.get(false)) {
	    	emailService.sendMakeMoreFriendsEmail(user);
	    }
	}
}

 

2-1. 이전에 배운거 응용

package com.fastcampus.functionalprogramming.chapter8;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import com.fastcampus.functionalprogramming.chapter8.model.User;
import com.fastcampus.functionalprogramming.chapter8.service.EmailService;

public class Chapter8Section8 {
	public static void main(String[] args) {
		User user1 = new User()
				.setId(101)
				.setName("Alice")
				.setEmailAddress("alice@fastcampus.co.kr")
				.setFriendUserIds(Arrays.asList(201, 202, 203, 204, 211, 212, 213, 214));
	    User user2 = new User()
	    		.setId(102)
	    		.setName("Bob")
	    		.setEmailAddress("bob@fastcampus.co.kr")
	    		.setFriendUserIds(Arrays.asList(204, 205, 206));
	    User user3 = new User()
	    		.setId(103)
	    		.setName("Charlie")
	    		.setEmailAddress("charlie@fastcampus.co.kr")
	    		.setFriendUserIds(Arrays.asList(204, 205, 207, 218));
	    
	    List<User> users = Arrays.asList(user1, user2, user3);
	    Map<Boolean, List<User>> userPartitions = users.stream().collect(Collectors.partitioningBy(user -> user.getFriendUserIds().size() > 5));
	    
	    EmailService emailService = new EmailService();
	    Consumer<User> play = user -> {
	    	emailService.sendPlayWithFriendsEmail(user);
	    };
	    
	    Consumer<User> make = user -> {
	    	emailService.sendMakeMoreFriendsEmail(user);
	    };
	    
	    sendMail(userPartitions.get(true), play);
	    sendMail(userPartitions.get(false), make);
	}
	
	public static void sendMail(List<User> user, Consumer<User> processer) {
		for (User eachUser: user) {
			processer.accept(eachUser);
		}
	}
}

'Backend > Java8' 카테고리의 다른 글

#33 Advanced Stream - Parallel Stream(병렬 Stream)  (0) 2022.10.22
#32 Advanced Stream - forEach  (0) 2022.10.21
#30 Advanced Stream - Grouping By  (1) 2022.10.19
#29 Advanced Stream - To Map  (0) 2022.10.18
#28 Advanced Stream - Collectors  (0) 2022.10.17
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/01   »
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
글 보관함