티스토리 뷰
Function, Consumer, Predicate, Supplier
public class FunctionalInterfaceExamples {
public static void main(String[] args) {
/**
* JAVA 8
* */
/**
* Function : 입력이 있으면 반드시 출력이 있다 (타입 변환)
*/
Function<String, Integer> toInt = value -> Integer.parseInt(value);
final Integer number = toInt.apply("100");
System.out.println(number);
// Function - identity
final Function<Integer, Integer> identity = Function.identity();
System.out.println(identity.apply(333));
/**
* Consumer : 리턴값이 없는 (소비만 한다)
*/
final Consumer<String> print = s -> System.out.println(s);
print.accept("Hello");
/**
*Predicate : 리턴값은 항상 boolean 이여야 한다.
*/
Predicate<Integer> isPositive = i -> i > 0;
Predicate<Integer> lessThan3 = i -> i < 3;
System.out.println(isPositive.test(1));
System.out.println(isPositive.test(0));
System.out.println(isPositive.test(-1));
//predicate 활용
List<Integer> numbers = Arrays.asList(-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5);
/////////////////////// boil code ///////////////////////
List<Integer> positiveNumbers = new ArrayList<>();
for (Integer num : numbers) {
if (isPositive.test(num)) {
positiveNumbers.add(num);
}
}
List<Integer> numbersLessThan3= new ArrayList<>();
for (Integer num : numbers) {
if (lessThan3.test(num)) {
numbersLessThan3.add(num);
}
}
System.out.println("positive integers: " + positiveNumbers);
System.out.println("numbersLessThan3 integers: " + numbersLessThan3);
/////////////////////// boil code ///////////////////////
/// private static <T> List<T> filter(List<T> list, Predicate<T> filter 메서드 사용
System.out.println("filter isPositive: " + filter(numbers, isPositive));
System.out.println("filter lessThan3: " + filter(numbers, lessThan3));
///////////////////////////////////////////////////////////////////////////////////////////////////
/**
* Supplier
* */
final Supplier<String> hellSupplier = () -> "Hello " ;
System.out.println(hellSupplier.get() + "world");
long start = System.currentTimeMillis();
printIfValidIndex(0, () -> getVeryExpensiveValue());
printIfValidIndex(-1, () -> getVeryExpensiveValue());
printIfValidIndex(-2, () -> getVeryExpensiveValue());
System.out.println("It took " + (System.currentTimeMillis() - start) / 1000 + " seconds");
}
private static String getVeryExpensiveValue() {
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "Geun ho";
}
// predicate 활용
private static <T> List<T> filter(List<T> list, Predicate<T> filter) {
List<T> result = new ArrayList<>();
for (T input : list) {
if (filter.test(input)) {
result.add(input);
}
}
return result;
}
// Supplier 활용
/*private static void printIfValidIndex(int number, String value) {
if (number >= 0) {
System.out.println("The value is " + value + " .");
} else {
System.out.println("Invalid");
}
}*/
private static void printIfValidIndex(int number, Supplier<String> valueSupplier) {
if (number >= 0) {
System.out.println("The value is " + valueSupplier.get() + " .");
} else {
System.out.println("Invalid");
}
}
}
public class FunctionInterfaceExamples {
public static void main(String[] args) {
final Product productA = new Product(1L, "A", new BigDecimal("10.00"));
final Product productB = new Product(2L, "B", new BigDecimal("55.50"));
final Product productC = new Product(3L, "C", new BigDecimal("17.45"));
final Product productD = new Product(4L, "D", new BigDecimal("23.00"));
final Product productE = new Product(5L, "E", new BigDecimal("110.00"));
final List<Product> products = Arrays.asList( productA, productB, productC, productD, productE );
final BigDecimal twenty = new BigDecimal("20");
List<Product> result = filter( products, product -> product.getPrice().compareTo(twenty) >= 0);
// DiscountedProducts
List<Product> expensiveProducts = filter(products, product -> product.getPrice().compareTo(new BigDecimal("50")) > 0);
List<DiscountedProducts> discountedProducts = map(expensiveProducts,
product -> new DiscountedProducts(product.getId(), product.getName(), product.getPrice().multiply(new BigDecimal("0.5"))));
//////////////////////////////////////////////////////////// println /////////////////////////////////////////////////////////////////////////////////
System.out.println("total products : " + result);
System.out.println("products <= 10 " + filter(products, product -> product.getPrice().compareTo(new BigDecimal("10")) <= 0));
System.out.println("expensive products : " + expensiveProducts);
System.out.println("discounted products : " + discountedProducts);
System.out.println("30 이하 products " + filter(discountedProducts, d-> d.getPrice().compareTo(new BigDecimal("30")) < 0));
/*
--> 이런 작업을 할 필요가 없다.
final List<BigDecimal> prices = map(products, product -> product.getPrice());
BigDecimal total = BigDecimal.ZERO;
for (final BigDecimal price : prices) {
total = total.add(price);
}
*/
BigDecimal total = total(products, product -> product.getPrice());
System.out.println("total : " + total);
BigDecimal DisCountedTotal = total(discountedProducts, product -> product.getPrice());
System.out.println("DisCountedTotal : " + DisCountedTotal);
Order order = new Order(1L, "on+1234", Arrays.asList(
new OrderItem(1L, productA, 2),
new OrderItem(2L, productB, 11),
new OrderItem(3L, productC, 10)
));
BigDecimal orderTotal = order.totalPrice();
System.out.println("OrderTotal : " + orderTotal);
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
} // end main
// 필터 compareTo 를 이용 1 , 0 , -1 를 가지고 Predicate 를 이용해서 boolean 결과값을 받고 쌓여진 List 목록을 받는다.
private static <T> List<T> filter(List<T> list, Predicate<T> predicate) {
final List<T> result = new ArrayList<>();
for (final T t: list) {
if (predicate.test(t)) {
result.add(t);
}
}
return result;
}
// List<?> 에 어떤 형을 넣어서 다른 형으로 변환 시킨다 (ex) expensiveProducts --> discountedProducts 로 변한
private static <T, R> List<R> map(List<T> list, Function<T, R> function) {
final List<R> result = new ArrayList<>();
for (final T t : list) {
result.add(function.apply(t));
}
return result;
}
// 어떤형을 넣든 BigDecimal 형을 변환이 된다면(Function 이용) total 값을 구할 수 있다.
private static <T> BigDecimal total(List<T> list, Function<T, BigDecimal> mapper) {
BigDecimal total = BigDecimal.ZERO;
for (final T t : list) {
total = total.add(mapper.apply(t));
}
return total;
}
/**
* lombok 이용
*
* 1.
* lib gradle(모듈레벨) 에
* dependency 에 추가
* compileOnly "org.projectlombok:lombok:1.16.18"
* annotationProcessor "org.projectlombok:lombok:1.16.18"
*
* 2. Annotation processors 에 Enable annotation processing 에 체크
*
* 3. Sysout.out.println 한글 변환
*
* 모듈 레벨에서
*
* dependency 밖에 선언
*
* compileJava.options.encoding = 'UTF-8'
* tasks.withType(JavaCompile){
* options.encoding = 'UTF-8'
* }
*/
@AllArgsConstructor
@Data
static class Product {
private Long id;
private String name;
private BigDecimal price;
}
@ToString(callSuper = true)
static class DiscountedProducts extends Product {
public DiscountedProducts(Long id, String name, BigDecimal price) {
super(id, name, price);
}
}
@AllArgsConstructor
@Data
static class OrderItem {
private Long id;
private Product product;
private int quantity;
public BigDecimal getItemTotal() {
return product.getPrice().multiply(new BigDecimal(quantity));
}
}
@AllArgsConstructor
@Data
static class Order {
private Long id;
private String orderNumber;
private List<OrderItem> items;
public BigDecimal totalPrice() {
return total(items, items -> items.getItemTotal());
}
}
} // end class
'RxJava ' 카테고리의 다른 글
fillter() 함수 (0) | 2019.02.13 |
---|---|
map 함수 (0) | 2019.02.07 |
flatMap() 함수 (0) | 2019.01.23 |
RxJava Subjsct class (0) | 2019.01.18 |