Java 8 Functinal Programming Tutorial.
Java 8 μ Lambda ννμκ³Ό Stream API λ₯Ό μ΄μ©νμ¬ Functinal νλ‘κ·Έλλ°μ μ§μνλ€. μ΄ νν 리μΌμμ μ¬μ μ μ μλ Functional interfacesμ Collctions API κ·Έλ¦¬κ³ Stream APIλ₯Ό ν΅ν΄ Java8 μ΄ μ΄λ€μμΌλ‘ Functioanl νλ‘κ·Έλλ°μ μ§μνλμ§ μμλ³Έλ€.
-
λͺ©μ°¨
- 1. Java8 Functional Programming μκ°
- 2. μ¬μ©λ²
- 3. μ¬μ μ μλ Functional InterFaces
- 4. Functional Inteface λ€μ μν‘μ λ§κ² μ¬μ©
- 5. Java 8 νμ₯
- 6. μμ
- 7. μμ½
- 8. μλ¬Έ
- 9. λ€μ΄λ‘λ μμ μ½λ
Java λ κ°μ²΄ μ§ν₯ νλ‘κ·Έλλ° μΈμ΄μ΄λ€.
Java8 μ Lambda ννμμ ν΅ν΄ Functional programming μ μ§μνλ€.
λλ€ ννμμ λ€μμ λ¬Έλ²μΌλ‘ νΉμ μ§μ΄ μ§λ€.
(μ½€λ§λ‘ ꡬλΆλ μ¬λ¬κ°μ§μ νλΌλ©ν°) -> {νλ μ΄μμ λ°λ μ²λ¦¬}
JDK μ μ»΄νμΌλ¬κ° type interface λ₯Ό μ§μνκΈ°μ λλ€ ννμμ λκ°μ§ λ°©λ²μΌλ‘ μ§§μ ννμ΄ κ°λ₯νλ€.
- νλΌλ©ν°μ νμ μ μ μΈ ν μ μλ€. μ»΄νμΌλ¬λ νλΌλ©ν°μ κ°μΌλ‘ νμ μ μ μΆ ν μ μλ€.
- λλ€ μ²λ¦¬μ λ°λκ° λ¨μΌ ννμμ΄λ©΄
returnν€μλλ₯Ό μ μΈμν¬μ μλ€.
λν λ€μμ μν©μμ μ’ λ λ¨μννμ΄ κ°λ₯νλ€.
- λ¨μΌ νλΌλ©ν°μμ κ΄νΈλ₯Ό μλ΅ ν μ μλ€.
- ννμμ λ°λκ° λ¨μΌ μ²λ¦¬μΌ κ²½μ° μ€κ΄νΈλ μλ΅ ν μ μλ€.
Functional programming μ νλΌλ©ν°λ Function μμ²΄λ‘ λ°ννμ¬ μ λ¬νλ κ³ κΈ°λ₯ Functionμ μ§μνλ€.
λν μλ‘μ΄ stream API λν κ³ κΈ°λ₯ Functionμ μ§μνλ€.
ν΄λΉ νν 리μΌμμλ Java8 μμ Functional νλ‘κ·Έλλ°μ κΈ°λ³Έμ μΌλ‘ μ¬μ μ μ μλ
μΈν°νμ΄μ€λ€κ³Ό Collections, κ·Έλ¦¬κ³ Stream API λ‘ μ€λͺ
νλ€.
νμ¬ κΈμ μμ λ λ€μμ λ²μ μΌλ‘ λΉλλκ³ μ€νλλ€.
- Java 1.8.101
- Maven 3.3.9
- Eclipse Oxygen
- JUnit 4.12
μ΄λ²μλ Junit λΌμ΄λΈλ¬λ¦¬λ₯Ό ν¬ν¨ν Maven Project λ₯Ό μμ±νλ€.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"<br>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"<br>
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><br>
<modelVersion>4.0.0</modelVersion><br>
<groupId>zheng.jcg.demo</groupId><br>
<artifactId>java8-demo</artifactId><br>
<version>0.0.1-SNAPSHOT</version><p></p>
<p> <dependencies><br>
<dependency><br>
<groupId>junit</groupId><br>
<artifactId>junit</artifactId><br>
<version>4.12</version><br>
<scope>test</scope><br>
</dependency><br>
</dependencies><br>
<build><br>
<plugins><br>
<plugin><br>
<artifactId>maven-compiler-plugin</artifactId><br>
<version>3.3</version><br>
<configuration><br>
<source>1.8</source><br>
<target>1.8</target><br>
</configuration><br>
</plugin><br>
</plugins><br>
</build><br>
</project></p>Functional Interface (FI) λ java.lang.object λ‘λΆν° μμλ°μ§ μμΌλ©° νλμ abstract λ©μλλ₯Ό
κ°μ§ μΈν°νμ΄μ€ μ΄λ€.
Functional Programming μ νκ°μ§ νΉμ§μ μμ Function μ΄λ€.
μμ Function μ μ
λ ₯κ³Ό μΆλ ₯μ μ²λ¦¬νλ€.
λν ν΄λΉ μ²λ¦¬λ μ΄λ ν μν©μμλ λ³νμ§ μλ κ²μ λͺ©μ μΌλ‘ νλ€.
κ·Έλ¬λ―λ‘ ν΄λΉ μ²λ¦¬λ μ΄λ ν μ¬μ΄λ μ΄ν©νΈλ λ°μνμ§ μλλ€.
νμ λμΌν μΆλ ₯κ³Ό μ
λ ₯μ μ²λ¦¬νλ€.
Java 8 μ 40κ°μ§ μ΄μμ μ¬μ μ μ μλ Functional interfaces λ₯Ό μ 곡νλ€. Consumer λ₯Ό μ μΈν λͺ¨λ FI λ μμ Functionλ€μ΄λ€.
Java8 μ°Έμ‘° λ©μλλ λλ€μμ λ¨ νκ°μ§ μ€νμ μν΄ μ§§κ² ννν μ μλ€. κ°λ°μλ λλ€μμ΄λ μ°Έμ‘° λ©μλλ₯Ό FI λ‘ μ¬μ©ν μ μλ€. Java8 Stream API λ μ¬μ μ μλ FIλ€μ Steam μ μν΄ μ¬μ©ν μ μλ€.
μ΄λ² μ₯μμλ κ³΅ν΅ Functional Interfaceλ€μ μ΄λ€μμΌλ‘ μ¬μ©ν μ§ JUnit ν΄λμ€λ₯Ό μμ±νμ¬ λ³΄μ¬μ€λ€.
Function FI λ νλμ νλΌλ©ν° λ°μ λ€μ΄λ©° νλμ κ²°κ³Όλ₯Ό λ°ννλ€.
Function FI λ abstract λ©μλμΈ apply(Object) λ₯Ό νΈμΆνλ€.
Java8 μ μμ λ°μ΄ν° νμ μ μν΄ κ°κ° μ¬μ©νκΈ° μ©μ΄ν FIλ€μ μ 곡νλ€: IntFunction, DoubleFunction, IntToDoubleFunction, IntToLongFunction, DoubleToIntFunction, DoubleToLongFunction, LongToDoubleFunction, κ·Έλ¦¬κ³ LongToIntFunction.
BitFunction FI λ λκ°μ§μ νλΌλ©ν°λ₯Ό λ§€κ°λ³μλ‘ λ°μΌλ©° μ²λ¦¬λ κ²°κ³Όλ₯Ό 리ν΄νλ€.
BitFunction FI λ abrtract λ©μλμΈ apply(Object, Object) λ₯Ό νΈμΆνλ€.
Java8 μ λν λκ°μ§ νλΌλ©ν°λ₯Ό λ§€κ² λ³μλ‘ λ°μΌλ©° μ²λ¦¬λ κ²°κ³Όλ₯Ό Doubleκ°, Intκ°, Long κ°μ λ°ννλ ToDoubleBiFunction, ToIntBiFunction, ToLongBiFunction λ₯Ό μ 곡νλ€.
μ΄λ² μ₯μμλ FunctionTest.java ν΄λμ€λ₯Ό λ€μμ μ€λͺ
νκΈ° μν΄ μμ±νμλ€.
Integerν΄λμ€λ₯ΌStringν΄λμ€λ‘ λ³ν- λ¬Έμμ΄μ κΈΈμ΄λ₯Ό
IntegerνμΌλ‘ λ°ν - λκ°μ§ Functionμ μλ‘μ΄ FunctionμΌλ‘ κ²°ν©
- 리μ€νΈμ μμ±λ€μ
Stream-map(Function <T, R>)λ₯Ό ν΅νμ¬ λ³ννλ€. IntFunction,DoubleFunction, λ±λ±μ μ¬μ©λ²μ 보μ¬μ€λ€.
FunctionTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiFunction;
import java.util.function.DoubleFunction;
import java.util.function.DoubleToIntFunction;
import java.util.function.DoubleToLongFunction;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.function.IntToDoubleFunction;
import java.util.function.IntToLongFunction;
import java.util.function.LongToDoubleFunction;
import java.util.function.LongToIntFunction;
import java.util.function.ToDoubleBiFunction;
import java.util.function.ToIntBiFunction;
import java.util.function.ToLongBiFunction;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Test;
import com.zheng.demo.DataUtil;
import com.zheng.demo.model.LoginUser;
public class FunctionTest {
@Test
public void BiFunction_concat_two_String() {
BiFunction<String, String, String> concat = (a, b) -> a + b;
String combinedStr = concat.apply("Today is", " a wonderful day");
assertEquals("Today is a wonderful day", combinedStr);
}
@Test
public void BiFunction_multiple_two_int() {
BiFunction<Integer, Integer, Integer> concat = (a, b) -> a * b;
Integer product = concat.apply(3, 4);
assertEquals(12, product.intValue());
}
@Test
public void DoubleFunction_convertDoubleToString_via_lambda() {
DoubleFunction<String> doubleToString = num -> Double.toString(num);
assertEquals("123.456", doubleToString.apply(123.456));
}
@Test
public void DoubleToIntFunction_convertDoubleToInt_via_lambda() {
DoubleToIntFunction doubleToInt = num -> (int) num;
assertEquals(123, doubleToInt.applyAsInt(123.456));
}
@Test
public void DoubleToLongFunction_convertDoubleToLong_via_lambda() {
DoubleToLongFunction doubleToLongFunc = num -> (long) num;
assertEquals(123789008080l, doubleToLongFunc.applyAsLong(123789008080.456));
}
@Test
public void Function_combine_TwoFunctions() {
Function<LoginUser, String> getUser = LoginUser::getUsertName;
Function<String, String> toUpper = String::toUpperCase;
Function<LoginUser, String> userNameMustBeUppercase = getUser.andThen(toUpper);
assertEquals("MARY", userNameMustBeUppercase.apply( DataUtil.buildLoginUser("Mary", "pwd123")));
}
@Test
public void Function_convertStringToInteger_via_methodReference() {
Function<String, Integer> convertToWordCount = String::length;
List<String> words = Arrays.asList("The", "That", "John", "Thanks");
List<Integer> wordsCounts = words.stream().map(convertToWordCount).collect(Collectors.toList());
assertEquals(3, wordsCounts.get(0).intValue());
assertEquals(4, wordsCounts.get(1).intValue());
assertEquals(4, wordsCounts.get(2).intValue());
assertEquals(6, wordsCounts.get(3).intValue());
}
@Test
public void IntFunction_convertIntegerToString_via_lambda() {
IntFunction<String> intToString = num -> Integer.toString(num);
assertEquals("123", intToString.apply(123));
}
@Test
public void IntFunction_via_lambda() {
IntFunction<Integer> powerValue = num -> num * num;
assertEquals(9, powerValue.apply(3).intValue());
}
@Test
public void IntToDoubleFunction_convertIntToDouble_via_lambda() {
IntToDoubleFunction intToDoubleFunc = num -> (double) num;
assertEquals(123, intToDoubleFunc.applyAsDouble(123), 0.1);
}
@Test
public void IntToLongFunction_convertIntToLong_via_lambda() {
IntToLongFunction intToLongFunc = num -> (long) num;
assertEquals(123456, intToLongFunc.applyAsLong(123456));
}
@Test
public void LongToDoubleFunction_convertLongToDouble_via_lambda() {
LongToDoubleFunction longToDoubleFunc = num -> (double) num;
assertEquals(123456, longToDoubleFunc.applyAsDouble(123456), 0.1);
}
@Test
public void LongToIntFunction_convertLongToInt_via_lambda() {
LongToIntFunction longToIntFun = num -> (int) num;
assertEquals(123456, longToIntFun.applyAsInt(123456));
}
@Test
public void stream_map_via_methodReference() {
Map<String, List<String>> awards = new HashMap<>();
awards.put("Mary", Arrays.asList("Math", "Spelling Bee"));
awards.put("Tom", Arrays.asList("Basketball", "Spelling Bee"));
awards.put("Allen", Arrays.asList("English", "Spelling Bee"));
Function<String, String> convertKeyToUppercase = String::toUpperCase;
List<String> uppercaseKeys = awards.entrySet().stream().map(e -> convertKeyToUppercase.apply(e.getKey()))
.collect(Collectors.toList());
assertTrue(uppercaseKeys.contains("MARY"));
assertTrue(uppercaseKeys.contains("TOM"));
assertTrue(uppercaseKeys.contains("ALLEN"));
}
@Test
public void stream_map_with_lambda() {
List<String> collected = Stream.of("Java", "Rocks").map(string -> string.toUpperCase())
.collect(Collectors.toList());
assertTrue(collected.contains("JAVA"));
assertTrue(collected.contains("ROCKS"));
}
@Test
public void ToDoubleBiFunction_power_two_int() {
ToDoubleBiFunction<Integer, Integer> concat = (a, b) -> Math.pow(a, b);
double powerRet = concat.applyAsDouble(5, 3);
assertEquals(125.0, powerRet, 0.1);
}
@Test
public void ToIntBiFunction_multiple_two_int() {
ToIntBiFunction<Integer, Integer> concat = (a, b) -> a * b;
Integer product = concat.applyAsInt(3, 4);
assertEquals(12, product.intValue());
}
@Test
public void ToLongBiFunction_power_two_int() {
ToLongBiFunction<Integer, Integer> concat = (a, b) -> (long) Math.pow(a, b);
Long powerRet = concat.applyAsLong(5, 3);
assertEquals(125, powerRet.intValue());
}
}Predicate FI λ νλμ λ§€κ²λ³μλ₯Ό λ°μ λ€μ΄λ©° Boolean κ°μ λ°ννλ€.
Predicate FI μ abstract λ©μλλ test(Object) μ΄λ€.
BiPredicate FI λ λκ°μ§μ λ§€κ² λ³μλ₯Ό λ°μλ€μ΄λ©° Boolean κ°μ λ°ννλ€.
Java8 μ λν μμ λ°μ΄ν° νμ
μ μν IntPredicate, LongPredicate, κ·Έλ¦¬κ³ DoublePredicate μ μ 곡νλ€.
μ΄λ² μ₯μμλ λ€μμ μ€λͺ
νκΈ° μν΄ PredicateTest.java λ₯Ό μμ±νλ€.
Integerκ° μ«μ ννκ° λ§λμ§ μ²΄ν¬νλ€.- 리μ€νΈμ μμ±μ
Stream-filter(Predicate <T, R>)μ μ΄μ©νμ¬ νν°λ§ νλ€. - λκ°μ§ Predicateλ₯Ό νλμ Predicateλ‘ ν©μΉλ€.
Longκ°μ 3μΌλ‘ λλμ μλμ§ μ²΄ν¬νλ€.Doubleκ°μ κ°μ λ§κ² μ²λ¦¬λλμ§ μ²΄ν¬νλ€.- μ΅μ΄ λ§€κ² λ³μ
Integerκ°μ΄ λλ²μ§Έ λ§€κ²λ³μ κ°λ³΄λ€ ν°μ§ 체ν¬νλ€. IntPredicateμDoublePredicateμ μ¬μ©λ²μ 보μ¬μ€λ€.
PredicateTest.java
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.function.BiPredicate;
import java.util.function.DoublePredicate;
import java.util.function.IntPredicate;
import java.util.function.LongPredicate;
import java.util.function.Predicate;
import java.util.stream.Stream;
import org.junit.Test;
public class PredicateTest {
@Test
public void BiPredicate_whichIsBigger() {
BiPredicate<Integer, Integer> isBigger = (x, y) -> x > y;
assertTrue(isBigger.test(5, 4));
assertTrue(isBigger.negate().test(4, 5));
}
@Test
public void DoublePredicate_test_isPositive() {
DoublePredicate isPositive = x -> x > 0;
assertTrue(isPositive.test(1.5));
assertFalse(isPositive.test(-1.7));
}
@Test
public void IntPredicate_test_isNagative() {
IntPredicate isNagative = x -> x < 0;
assertTrue(isNagative.test(-1));
assertFalse(isNagative.test(1));
}
@Test
public void LongPredicate_test_isDivisibleByThree() {
LongPredicate isDivisibleBy3 = x -> x % 3 == 0;
assertTrue(isDivisibleBy3.test(12));
assertFalse(isDivisibleBy3.test(11));
}
@Test
public void Predicate_combine_two_predicates() {
// takes one argument and return a boolean
Predicate<String> stringIsLongerThanTen = s -> s.length() > 10;
assertTrue(stringIsLongerThanTen.test("This string is longer than 10"));
assertFalse(stringIsLongerThanTen.test("short"));
Predicate<String> stringStartWithA = s -> s.startsWith("A");
assertTrue(stringStartWithA.test("Apple is a fruit"));
Predicate<String> startWithAandLongerThan10 = stringIsLongerThanTen.and(stringStartWithA);
assertTrue(startWithAandLongerThan10.test("Apple is a fruit which grows everywhere."));
}
@Test
public void Predicate_test_integer_isEven() {
Predicate<Integer> isEven = s -> s % 2 == 0;
assertTrue(isEven.test(4));
assertFalse(isEven.test(5));
}
@Test
public void stream_filter_via_lambda() {
Stream.of("Apple", "Pear", "Banana", "Cherry", "Apricot").filter(fruit -> {
System.out.println("filter:" + fruit);
return fruit.startsWith("A");
}).forEach(fruit -> System.out.println("Started with A:" + fruit));
}
}Supplier FI λ λ§€κ²λ³μκ° μμΌλ κ²°κ³Ό κ°μ λ°ννλ€.
Supplier FI μ abstract method λ get() μ΄λ€.
보ν΅, Java8 μμ μμ λ°μ΄ν° νμ
μ μ¬μ©νκΈ° νΈνκ² Interfaceλ₯Ό μ 곡νλ€ : IntSupplier, DoubleSupplier, BooleanSupplier, κ·Έλ¦¬κ³ LongSupplier.
μ΄λ²μ₯μμλ SupplierTest.java ν΄λμ€λ₯Ό λ€μμ μ€λͺ
νκΈ° μν΄ μμ±νλ€.
stringκ°μ λ°ννλ€.trueκ°μ λ°ννλ€.- μ΅λ
Integerκ°μ λ°ννλ€. - μ΅λ
Longκ°μ λ°ννλ€. piκ°μ λ°ννλ€.
SupplierTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.function.BooleanSupplier;
import java.util.function.DoubleSupplier;
import java.util.function.IntSupplier;
import java.util.function.LongSupplier;
import java.util.function.Supplier;
import org.junit.Test;
public class SupplierTest {
@Test
public void BooleanSupplier_getAsBoolean() {
BooleanSupplier booleanSupplier = () -> true;
assertTrue(booleanSupplier.getAsBoolean());
}
@Test
public void DoubleSupplier_getAsDouble() {
DoubleSupplier pi = () -> Math.PI;
assertEquals(3.14, pi.getAsDouble(), 0.01);
}
@Test
public void IntSupplier_getAsInt() {
IntSupplier maxInteger = () -> Integer.MAX_VALUE;
assertEquals(2147483647, maxInteger.getAsInt());
}
@Test
public void LongSupplier_getAsLong() {
LongSupplier maxLongValue = () -> Long.MAX_VALUE;
assertEquals(9223372036854775807l, maxLongValue.getAsLong());
}
@Test
public void Supplier_AString() {
Supplier<String> message = () -> "Mary is fun";
assertEquals("Mary is fun", message.get());
}
}Consumer FI λ νλμ λ§€κ² λ³μλ₯Ό κ°μ§μ§λ§ κ²°κ³Όκ°μ λ°ννμ§ μλλ€.
Consumer FI μ abstract method λ accept(Object) μ΄λ€.
보ν΅, Java λν μμ λ°μ΄ν° νμ
μ μ¬μ©νκΈ° νΈνκ² Interfaceλ₯Ό μ 곡νλ€: IntConsumer, LongConsumer, DoubleConsumer, BiConsumer, ObjtIntConsumer, ObjLongConsumer, and ObjDoubleconsumer.
μ£Όμ: XXConsumer FIλ€μ μ¬μ΄λ μ΄ν©νΈλ₯Ό νμ©νκ²λ μ€κ³ λμ΄ μλ€.
μ΄λ² μ₯μμλ ConsumerTest.java ν΄λμ€λ₯Ό λ€μμ μ€λͺ
νκΈ° μν΄ μμ±νλ€.
- μλ¬Έμλ₯Ό λ³νν μ΄ν λ¬Έμμ΄μ μΆλ ₯νλ€.
- λ¬Έμμ΄μ μΆλ ₯νλ€.
- λκ°μ§μ λ¬Έμμ΄μ μΆλ ₯νλ€.
- μ¬λλ€κ³Ό λ§λ μΌ μ΄νμ λ λλ₯Ό μΆλ ₯νλ€.
- ꡬμ λλ λ₯Ό κ³μ°νλ€.
ConsumerTest.java
import java.util.Arrays;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.DoubleConsumer;
import java.util.function.IntConsumer;
import java.util.function.LongConsumer;
import java.util.function.ObjDoubleConsumer;
import java.util.function.ObjIntConsumer;
import java.util.function.ObjLongConsumer;
import org.junit.Test;
import com.zheng.demo.DataUtil;
import com.zheng.demo.model.Contact;
public class ConsumerTest {
@Test
public void BiConsumer_printout() {
BiConsumer<String, String> echo = (x, y) -> {
System.out.println(x);
System.out.println(y);
};
echo.accept("This is first line.", "Here is another line");
}
@Test
public void Consumer_convertToLowercase_via_lambda() {
Consumer<String> convertToLowercase = s -> System.out.println(s.toLowerCase());
convertToLowercase.accept("This Will convert to all lowercase");
}
@Test
public void Consumer_print_prefix() {
Consumer<String> sayHello = name -> System.out.println("Hello, " + name);
for (String name : Arrays.asList("Mary", "Terry", "John")) {
sayHello.accept(name);
}
}
@Test
public void Consumer_print_via_methodreferce() {
Consumer<String> output = System.out::println;
output.accept("This will be printed out.");
}
@Test
public void DoubleConsumer_printout() {
DoubleConsumer echo = System.out::println;
echo.accept(3.3);
}
@Test
public void IntConsumer_printout() {
IntConsumer echo = System.out::println;
echo.accept(3);
}
@Test
public void LongConsumer_printout() {
LongConsumer echo = System.out::println;
echo.accept(3l);
}
@Test
public void ObjDoubleConsumer_caculate_circle_circumference() {
ObjDoubleConsumer<Double> circleCircumference = (r, p) -> System.out.println("Circumference: " + 2 * r * p);
circleCircumference.accept(new Double(4.0), Math.PI);
}
@Test
public void ObjIntConsumer_alterContactAge() {
ObjIntConsumer<Contact> addThreeYear = (c, a) -> {
c.setAge(c.getAge() + a);
System.out.println("Updated contact" + c);
};
addThreeYear.accept(DataUtil.buildContact("mzheng", "pwd", 40), 3);
}
@Test
public void ObjLongConsumer() {
ObjLongConsumer<String> appendex = (m, l) -> {
System.out.println("Append " + m + l);
};
appendex.accept("test message", 10l);
}
}UnaryOperator FI λ νΉλ³ν νΌ μ°μ°μμ κ²°κ³Όκ° λμΌν Function μ΄λ€.
UnaryOperator FI μ abstract method λ apply(Object) μ΄λ€.
보ν΅, Java8μ μμ νμ
μ μν΄ κ°κ°μ ν΄λμ€λ₯Ό μ 곡νλ€.: IntUnaryOperator, DoubleUnaryOperator, κ·Έλ¦¬κ³ LongUnaryOperator.
μ΄λ² μ₯μμλ UnaryOperatorTest.java ν΄λμ€λ₯Ό λ€μμ μ€λͺ
νκΈ° μν΄ μμ±νλ€.
- λ¬Έμμ΄μ λλ¬Έμ ν¬λ©§μΌλ‘ λ³ννλ€.
- λ¬Έμμ΄μ λ€λ₯Έ λ¬Έμμ΄κ³Ό ν©μΉλ€.
- μ«μμ΄ κ°μ Double κ°μΌλ‘ λ°ννλ€.
- λ§€κ²λ³μμ κ°μ μ°μ°μ΄ν Long νκ°μΌλ‘ λ°ννλ€.
- λ§€κ²λ³μμ κ°μ μ°μ°μ΄ν Double νκ°μΌλ‘ λ°ννλ€.
UnaryOperatorTest.java
import static org.junit.Assert.assertEquals;
import java.util.function.DoubleUnaryOperator;
import java.util.function.IntUnaryOperator;
import java.util.function.LongUnaryOperator;
import java.util.function.UnaryOperator;
import org.junit.Test;
public class UnaryOperatorTest {
@Test
public void UnaryOperator_convertToUppdercase_via_lamdba() {
UnaryOperator<String> convertToUppercase = msg -> msg.toUpperCase();
String uppString = convertToUppercase.apply("this will be all uppercase");
assertEquals("THIS WILL BE ALL UPPERCASE", uppString);
}
@Test
public void UnaryOperator_concatString_via_methodReference() {
UnaryOperator<String> sayHi = "Hi, "::concat;
String concatString = sayHi.apply("Mary");
assertEquals("Hi, Mary", concatString);
}
@Test
public void IntUnaryOperator_doubleIt() {
IntUnaryOperator doubledIt = x -> x * 2;
assertEquals(24, doubledIt.applyAsInt(12));
}
@Test
public void LongUnaryOperator_squareIt() {
LongUnaryOperator squareIt = x -> x * x;
assertEquals(144, squareIt.applyAsLong(12));
}
@Test
public void DoubleUnaryOperator_squareIt() {
DoubleUnaryOperator squareIt = x -> x * x;
assertEquals(144, squareIt.applyAsDouble(12), 0.1);
}
}BinaryOperator FI λ νΉλ³ν νΌ μ°μ°μμ κ²°κ³Όκ° λμΌν Function μ΄λ€.
BinaryOperator FI μ abstract method λ apply(Object) μ΄λ€.
보ν΅, Java8μ int, long, double κ°κ°μ λ°μ΄ν° νμ
μΌλ‘μ IntBinaryOperator, LongBinaryOperator, κ·Έλ¦¬κ³ DoubleBinaryOperator λ₯Ό μ 곡νλ€.
μ΄λ² μ₯μμλ BinaryOperatorTest.java ν΄λμ€λ₯Ό λ€μμ μ€λͺ
νκΈ° μν΄ μμ±νλ€.
- λκ°μ μ«μλ₯Ό λνλ€.
- λ€μν μ«μ νμ μ λνλ€.
- λ μ«μμ κ±°λ μ κ³±μ μ²λ¦¬νλ€.
BinaryOperatorTest.java
import static org.junit.Assert.assertEquals;
import java.util.function.BinaryOperator;
import java.util.function.IntBinaryOperator;
import java.util.function.LongBinaryOperator;
import java.util.function.DoubleBinaryOperator;
import org.junit.Test;
public class BinaryOperatorTest {
@Test
public void BinaryOperator_add_via_lambda() {
BinaryOperator<Integer> add = (a, b) -> a + b;
Integer sum = add.apply(10, 12);
assertEquals(22, sum.intValue());
}
@Test
public void IntBinaryOperator_add_two_numbers() {
IntBinaryOperator add2 = (a, b) -> a + b;
int sum = add2.applyAsInt(10, 12);
assertEquals(22, sum);
}
@Test
public void LongBinaryOperator_mutiple_two_numbers() {
LongBinaryOperator add2 = (a, b) -> a * b;
long product = add2.applyAsLong(10, 12);
assertEquals(120, product);
}
@Test
public void DoubleBinaryOperator_power_two_number() {
DoubleBinaryOperator add2 = (a, b) -> Math.pow(a, b);
double powerRet = add2.applyAsDouble(10, 2);
assertEquals(100, powerRet, 001);
}
}Java8 μ μΈν°νμ΄μ€λ₯Ό FI λ‘ νμνλ μλ‘μ΄ μ΄λ
Έν
μ΄μ
@FunctionalInterface λ₯Ό μ 곡νλ€.
Java μ»΄νμΌλ¬λ νμλ μΈν°νμ΄μ€κ° νλμ΄μμ abstract λ©μλλ₯Ό κ°μ§λ μμΈλ₯Ό λμ§λ€.
μ΄λ² μ₯μμλ λκ°μ FIλ₯Ό μμ±νμ¬ Java μ΄ν리μΌμ΄μ μμ μ¬μ©λλμ§ λ€μμ μ¬λ‘λ‘ λ³΄μ¬μ§λ€.
IntegerCalculatorν΄λμ€λ@FunctionalInterfaceμ΄λ Έν μ΄μ μ κ°μ§λ€.GreetFunctionν΄λμ€λ@FunctionalInterfaceμ΄λ Έν μ΄μ μμ΄ μ²λ¦¬λλ€.
μ΄λ² μ₯μμλ IntegerCalcuator.java λ₯Ό νλμ λ©μλμΈ calcuate μ ν¨κ» μμ±νλ€.
IntegerCalcuator.java
@FunctionalInterface
public interface IntegerCalculator {
int caculate(int x, int y);
}μ΄λ² μ₯μμλ GreetingFunction.java λ₯Ό νλμ λ©μλμΈ speak μ ν¨κ» μμ±νλ€.
Java μ»΄νμΌλ¬λ ν΄λΉ ν΄λμ€λ₯Ό @FunctionalInterface μ΄λ
Έν
μ΄μ
μμ΄ FI λ‘ μ·¨κΈνλ€.
GreetingFunction.java
public interface GreetingFunction {
void speak(String message);
}μ΄λ² μ₯μμλ FPDemo.java ν΄λμ€λ₯Ό λ€μμ μ€λͺ
νκΈ° μν΄ μμ±νλ€.
- λκ°μ μ«μκ° λνκΈ°, λΉΌκΈ°, κ³±νκΈ° κ³μ°μ΄ λλμ§μ λν΄ μ²λ¦¬
- μ΄λ€μμΌλ‘ μ¬λμ μ΄λνλμ§
FPDemo.java
public class FPDemo {
public static void main(String[] args) {
GreetingFunction greeting = message -> System.out.println("Hello " + message + "!");
greeting.speak("Tom");
greeting.speak("Mary");
caculateTwoNumbers(3, 4);
caculateTwoNumbers(3, 0);
}
private static void caculateTwoNumbers(int x, int y) {
IntegerCalculator add = (a, b) -> a + b;
IntegerCalculator diff = (a, b) -> a - b;
IntegerCalculator divide = (a, b) -> (b == 0 ? 0 : a / b);
System.out.println(x + " + " + y + " = " + add.caculate(x, y));
System.out.println(x + " - " + y + " = " + diff.caculate(x, y));
System.out.println(x + " / " + y + " = " + divide.caculate(x, y));
}
}Java8 μ Collection ν΄λμ€λ₯Ό sort, max, min λ©μλλ₯Ό νμ©νμ¬ νμ₯ νλ€.
ν΄λΉ λ©μλ λ€μ comparator λ₯Ό νλΌλ©ν°λ‘ Functional interface λ₯Ό μ²λ¦¬ν μ μλ€.
Java8 Stream ν΄λμ€ API λ λ§€κ² λ³μλ‘ Functional interface λ₯Ό λ°μ λ€μ΄λ λ©μλμΈ
map, filter, sorted, min, max, reduce λ₯Ό μ 곡νλ€.
Collections ν΄λμ€μ Comparator μΈν°νμ΄μ€λ Java8 μμ νμ₯ λμλ€.
Comparator λ @FunctionalInterface μ΄λ
Έν
μ΄μ
μ΄ ν¬ν¨λμλ€.
λν Collectionsμ sort λ©μλλ Comparatorμ λ§€κ² λ³μλ‘ μ²λ¦¬ λλ€.
μ΄λ² μ₯μμλ CollectionsTest.java λ₯Ό λ€μμ κ²½μ°λ₯Ό μ€λͺ
νκΈ° μν΄ μμ±νλ€.
- μ°λ½μ²λ₯Ό λμ΄μμΌλ‘ μ λ ¬νλ€.
- λ¬Έμμ΄μ 리μ€νΈλ₯Ό μ λ ¬νλ€.
- JDK7μμμ μ λ ¬μ²λ¦¬μ λΉκ΅νλ€.
CollectionsTest.java
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.junit.Test;
import com.zheng.demo.dao.ContactDao;
import com.zheng.demo.model.Contact;
public class CollectionsTest {
private ContactDao contDao = new ContactDao();
@Test
public void Collections_sort_by_contact_age() {
Comparator<Contact> contactComparator = Comparator.comparing(Contact::getAge);
List<Contact> contacts = contDao.findAllContacts();
Collections.sort(contacts, contactComparator);
System.out.println("Sorted contact");
contacts.stream().forEach(System.out::println);
Contact oldertContact = Collections.max(contacts, contactComparator );
assertEquals(57, oldertContact.getAge());
Contact youngestContact = Collections.min(contacts, contactComparator );
assertEquals(21, youngestContact.getAge());
}
@Test
public void Collections_sortWithInferType() {
List<String> names = Arrays.asList("Allen", "Matt", "Mary", "Megan", "Alex");
Collections.sort(names, (a, b) -> a.compareTo(b));
System.out.println("Sorted names: " + names);
}
@Test
public void sortBeforeJava8() {
List<String> names = Arrays.asList("Allen", "Matt", "Mary", "Megan", "Alex");
Collections.sort(names, new Comparator<String>() {
@Override
public int compare(String a, String b) {
return b.compareTo(a);
}
});
}
}Java8 Stream API λ μμ±λ€μ 컬λ μ μ²λ¦¬μ λ°λ³΅λ¬Έμ μ§κ΄μ μΌλ‘ μ²λ¦¬νλ€. κ°λ°μλ λμ΄μ find, search, κ°μ²΄μ μμ±μ 컬λ μ μμ νν°λ§ νλκ²μ μ¬μ©νμ§ μμλ λλ€.
μ΄λ² μ₯μμλ StreamTest.java ν΄λμ€λ₯Ό λ€μμ μ€λͺ
νκΈ° μν΄ μμ±νλ€.
Forλ°λ³΅λ¬ΈμΌλ‘ κ°μ²΄ μμ±λ€μ λ°λ³΅μ²λ¦¬ νλ€.Iteratorλ‘ κ°μ²΄ μμ±λ€μ λ°λ³΅ μ²λ¦¬νλ€.StreamAPI μforeach(Consumer<T>)λ‘ μ²λ¦¬νλ€.- κ°μ²΄μ 리μ€νΈλ₯Ό νΉμ κ°μ²΄ μμ±μΌλ‘ νν°λ§ μ²λ¦¬νλ€.
- κ°μ²΄μ 리μ€νΈ μμ μλ κ°μ²΄ μμ±λ€μ λ³κ²½νλ€.
- κ°μ²΄μ 리μ€νΈμμ μ΅μκ°κ³Ό μ΅λκ°μ κ°λ€μ νν°λ§ νκ³ λν μ λ ¬νλ€.
StreamTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.Before;
import org.junit.Test;
public class StreamTest {
private List<String> userNames;
@Test
public void search() {
Predicate<String> startWithA = name -> name.startsWith("a");
List<String> startWithANames = userNames.stream().filter(startWithA).collect(Collectors.toList());
assertEquals("aWang", startWithANames.get(0));
}
@Test
public void IntStream_sum() {
int sum = IntStream.of(1, 3, 5, 7, 9).sum();
assertEquals(25, sum);
}
@Test
public void tranform() {
List<String> uppercaseNames = userNames.stream().map(String::toUpperCase).collect(Collectors.toList());
assertTrue(uppercaseNames.contains("MZHENG"));
assertTrue(uppercaseNames.contains("AWANG"));
assertTrue(uppercaseNames.contains("TCHANG"));
}
@Test
public void min() {
Comparator<String> comparator = Comparator.comparing(String::length);
Optional<String> shortestName = userNames.stream().min(comparator );
assertTrue(shortestName.isPresent());
assertEquals("aWang", shortestName.get());
Optional<String> longestName = userNames.stream().max(comparator );
assertTrue(longestName.isPresent());
assertEquals("mzheng", longestName.get());
}
@Test
public void print_elelments_via_loop() {
for (String name : userNames) {
System.out.println(name);
}
}
@Test
public void print_elements_via_Iterator() {
Iterator<String> i = userNames.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
@Test
public void print_elemetns_via_Stream() {
// Internal iteration
userNames.stream().forEach(System.out::println);
}
@Before
public void setup() {
userNames = Stream.of("mzheng", "tChang", "aWang").collect(Collectors.toList());
}
@Test
public void sort() {
List<String> sortedNames = userNames.stream().sorted().collect(Collectors.toList());
assertEquals("aWang", sortedNames.get(0));
assertEquals("mzheng", sortedNames.get(1));
assertEquals("tChang", sortedNames.get(2));
}
}ν΄λΉ λΈλ‘κ·Έ κΈμμ κ°κ°μ Java μ¬μ μ μλ Function interface λ€μ ν
μ€νΈ νμκ³ ,
λκ°μ κ°κ° μμ λ Functiona interface λ€μ ν
μ€νΈ νμΌλ©°,
Comparator, Collections, κ·Έλ¦¬κ³ Stream μ μ²λ¦¬λ₯Ό νμΈνλ€.
μ΄λ² μ₯μμλ μ€μ λ‘ μ¬μ©λλ μ¬λ‘λ₯Ό μ€λͺ
νλ€.
ν΄λΉ μμ μ μ΄ν리μΌμ΄μ μμλ λ€μ λκ°μ§μ μꡬμ¬νμ΄ μλ€κ³ κ°μ νλ€.
- λ°μ΄ν° λ² μ΄μ€μμ μ°λ½μ²λ₯Ό κ°μ Έμ¨λ€.
- λ‘κ·ΈμΈ μ μ μ μ°λ½μ²λ₯Ό λ³κ²½νλ€.
μ΄λ² μ₯μμλ μ±, μ΄λ¦, λμ΄, μ μ μ΄λ¦, λΉλ°λ²νΈλ₯Ό ν¬ν¨ν Contact.java ν΄λμ€λ₯Ό μμ±νλ€.
Contact.java
public class Contact {
private String firstName;
private String lastName;
private String userName;
private String password;
private int age;
public Contact() {
super();
}
public Contact(String firstName, String lastName, String userName, String password, int age) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.userName = userName;
this.password = password;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Contact [firstName=" + firstName + ", lastName=" + lastName + ", userName=" + userName + ", password="
+ password + ", age=" + age + "]";
}
}μ΄λ² μ₯μμλ username κ³Ό passwordλ₯Ό ν¬ν¨ν LoginUser.java ν΄λμ€λ₯Ό μμ±νλ€.
LoginUser.java
public class LoginUser {
private String userName;
private String password;
public String getUsertName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "LoginUser [userName=" + userName + ", password=" + password + "]";
}
}μ΄λ² μ₯μμλ DataUtil.java ν΄λμ€λ₯Ό μμ±νλ€.
DataUtil.java
import java.util.ArrayList;
import java.util.List;
public class DataUtil {
public static List<Contact> getListOfContacts() {
List<Contact> contacts = new ArrayList<>();
contacts.add(new Contact("Becky", "Zheng", "bzheng", "pwd1234@", 48));
contacts.add(new Contact("Alex", "Change", "aChange", "pwd987$", 21));
contacts.add(new Contact("Caleb", "Wang", "cWang", "pwd2345#", 57));
return contacts;
}
public static Contact buildContact(String username, String pwd, int age) {
Contact cnt = new Contact();
cnt.setUserName(username);
cnt.setPassword(pwd);
cnt.setAge(age);
return cnt;
}
public static LoginUser buildLoginUser(String userName, String pwd) {
LoginUser user = new LoginUser();
user.setUserName(userName);
user.setPassword(pwd);
return user;
}
public static LoginUser toUser(Contact contact) {
LoginUser user = new LoginUser();
user.setPassword(contact.getPassword());
user.setUserName(contact.getUserName().toUpperCase());
return user;
}
}μ΄λ² μ₯μμλ λͺ¨λ μ°λ½μ²λ₯Ό μ°Ύλ λ©μλλ₯Ό ν¬ν¨ν ConctactDao.java ν΄λμ€λ₯Ό μμ±νλ€.
ContactDao.java
package com.zheng.demo.dao;
import java.util.List;
import com.zheng.demo.model.Contact;
import com.zheng.demo.model.DataUtil;
public class ContactDao {
public List<Contact> findAllContacts(){
return DataUtil.getListOfContacts();
}
}μ΄λ² μ₯μμλ ContactDaoTest.java ν΄λμ€λ₯Ό μμ±νλ€.
ContactDaoTest.java
import static org.junit.Assert.assertEquals;
import java.util.List;
import org.junit.Test;
import com.zheng.demo.model.Contact;
public class ContactDaoTest {
private ContactDao testClass = new ContactDao();
@Test
public void findAllContacts() {
List<Contact> allContacts = testClass.findAllContacts();
assertEquals(3, allContacts.size());
}
}μ΄λ² μ₯μμλ Contact ν΄λμ€λ₯Ό LoginUser ν΄λμ€λ‘ λ³ννλ DataMapper ν΄λμ€λ₯Ό μμ±νλ€.
DataMapper.java
import com.zheng.demo.model.Contact;
import com.zheng.demo.model.DataUtil;
import com.zheng.demo.model.LoginUser;
public class DataMapper {
public LoginUser toUser(Contact contact) {
return DataUtil.toUser(contact);
}
}μ΄λ² μ₯μμλ DataMapperTest.java ν΄λμ€λ₯Ό μμ±νλ€.
DataMapperTest.java
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Test;
import com.zheng.demo.model.Contact;
import com.zheng.demo.model.LoginUser;
public class DataMapperTest {
private DataMapper dto = new DataMapper();
@Test
public void toUser() {
Contact contact = new Contact("firstName", "lastName", "userName", "password", 40);
LoginUser user = dto.toUser(contact);
assertNotNull(user);
assertEquals("USERNAME", user.getUsertName());
assertEquals("password", user.getPassword());
}
}μ΄λ² μ₯μμλ Contact ν΄λμ€λ₯Ό LoginUser ν΄λμ€λ‘ λ³νν μ μλ μ¬λ¬κ°μ§ λ°©λ²μ΄ μ²λ¦¬λλ LoginUserService.java ν΄λμ€λ₯Ό μμ±νλ€.
ν΄λΉ ν΄λμ€λ κ°κ°μ κΈ°λ₯μ΄ μλ€.
- Java 8 λ©μλ μ°Έμ‘° (μΈκ°μ§ ν¬λ©§μ΄ ν¬ν¨λ λ²μ )
- Java 8 λλ€ ννμ (μΈκ°μ§ ν¬λ©§μ΄ ν¬ν¨λ λ²μ )
- Java 8 λλ€ ννμμΌλ‘ λͺ λͺ λ κΈ°λ₯
Java Forλ°λ³΅λ¬Έ
LoginUserService.java
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import com.zheng.demo.dao.ContactDao;
import com.zheng.demo.model.Contact;
import com.zheng.demo.model.DataUtil;
import com.zheng.demo.model.LoginUser;
public class LoginUserService {
ContactDao contactDao = new ContactDao();
DataMapper dto = new DataMapper();
public List<LoginUser> getAllUser_java8Style_Lambda_1() {
return contactDao.findAllContacts().stream().map(contact -> {
LoginUser user = new LoginUser();
user.setPassword(contact.getPassword());
user.setUserName(contact.getUserName().toUpperCase());
return user;
}).collect(Collectors.toList());
}
public List<LoginUser> getAllUser_java8Style_Lambda_2() {
return contactDao.findAllContacts().stream().map(c -> {
return toUser(c);
}).collect(Collectors.toList());
}
public List<LoginUser> getAllUser_java8Style_Lambda_3() {
return contactDao.findAllContacts().stream().map(c -> toUser(c)).collect(Collectors.toList());
}
public List<LoginUser> getAllUser_java8Style_methodReference_1() {
return contactDao.findAllContacts().stream().map(DataUtil::toUser).collect(Collectors.toList());
}
public List<LoginUser> getAllUser_java8Style_methodReference_2() {
return contactDao.findAllContacts().stream().map(this::toUser).collect(Collectors.toList());
}
public List<LoginUser> getAllUser_java8Style_methodReference_best() {
return contactDao.findAllContacts().stream().map(dto::toUser).collect(Collectors.toList());
}
public List<LoginUser> getAllUser_java8Style_namedLambda() {
Function<Contact, LoginUser> convertContactToLoginUser = contact -> {
return toUser(contact);
};
return contactDao.findAllContacts().stream().map(convertContactToLoginUser).collect(Collectors.toList());
}
public List<LoginUser> getAllUser_loopStyle() {
List<Contact> allContacts = contactDao.findAllContacts();
List<LoginUser> allUser = new ArrayList<>();
for (Contact contact : allContacts) {
allUser.add(toUser(contact));
}
return allUser;
}
private LoginUser toUser(Contact contact) {
LoginUser user = new LoginUser();
user.setPassword(contact.getPassword());
user.setUserName(contact.getUserName().toUpperCase());
return user;
}
}μ΄λ² μ₯μμλ LoginUserServiceTest.java ν΄λμ€λ₯Ό μμ±νλ€.
LoginUserServiceTest.java
import static org.junit.Assert.assertTrue;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import org.junit.Test;
import com.zheng.demo.model.LoginUser;
public class LoginUserServiceTest {
private LoginUserService testService = new LoginUserService();
@Test
public void getAllUser_java8Style_Lambda_1() {
List<LoginUser> allusers = testService.getAllUser_java8Style_Lambda_1();
assertTrue(allusers.size() == 3);
validate(allusers);
}
@Test
public void getAllUser_java8Style_Lambda_2() {
List<LoginUser> allusers = testService.getAllUser_java8Style_Lambda_2();
assertTrue(allusers.size() == 3);
validate(allusers);
}
@Test
public void getAllUser_java8Style_Lambda_3() {
List<LoginUser> allusers = testService.getAllUser_java8Style_Lambda_3();
assertTrue(allusers.size() == 3);
validate(allusers);
}
@Test
public void getAllUser_java8Style_methodReference_1() {
List<LoginUser> allusers = testService.getAllUser_java8Style_methodReference_1();
assertTrue(allusers.size() == 3);
validate(allusers);
}
@Test
public void getAllUser_java8Style_methodReference_2() {
List<LoginUser> allusers = testService.getAllUser_java8Style_methodReference_2();
assertTrue(allusers.size() == 3);
validate(allusers);
}
@Test
public void getAllUser_java8Style_methodReference_best() {
List<LoginUser> allusers = testService.getAllUser_java8Style_methodReference_best();
assertTrue(allusers.size() == 3);
validate(allusers);
}
@Test
public void getAllUser_java8Style_namedLambda() {
List<LoginUser> allusers = testService.getAllUser_java8Style_namedLambda();
assertTrue(allusers.size() == 3);
validate(allusers);
}
@Test
public void getAllUser_loopStyle() {
List<LoginUser> allusers = testService.getAllUser_loopStyle();
assertTrue(allusers.size() == 3);
validate(allusers);
}
private void validate(List<LoginUser> allusers) {
Consumer<LoginUser> printOutUser = System.out::println;
allusers.stream().forEach(printOutUser );
Predicate<LoginUser> foundMary = e -> e.getUsertName().equalsIgnoreCase("bzheng") ;
List<LoginUser> foundusers = allusers.stream().filter(foundMary ).collect(Collectors.toList());
assertTrue(foundusers.size() == 1);
}
}ν΄λΉ νν 리μΌμμλ μ¬μ μ μ μλ functional interface λ€μ μ΄λ€μμΌλ‘ μ¬μ©νλμ§μ λν΄ λ³΄μ¬μ€¬μΌλ©°, λν κ°κ° λ§μΆ€ Functional interface μ μ¬μ©λ²μ 보μ¬μ€¬λ€.
μ΄ν Stream API λ₯Ό λ€λ£¨μ΄ 보μμΌλ©°, μ΄ν μ€ μ²λ¦¬μ μ¬μ©ν μ μλ μμ λ€μ μ²λ¦¬νλ€.
Functional interface λ₯Ό μ§μνλ Java 8 μ 2014λ
3μ 18μΌμ λ¦΄λ¦¬μ¦ λμλ€.
Java λ μλ Functional νλ‘κ·Έλ¨μ μ§μνμ§ μμλ€.
Functional programming μ Function μμ κ²°κ³Όλ₯Ό 리ν΄νλκ²μ ν¬μ»€μ± λμ΄ μμΌλ©° κ°μ²΄ μ§ν₯λ³΄λ€ μ’ λ μ’μ μ±λ₯μ 보μ¬μ€λ€.
Java 8 Functional Programming Tutorial By Mary Zheng
μμ΄ κ³΅λΆλ₯Ό μν΄ νΌμμ΅λλ€. μ μκΆμ΄ λ¬Έμ κ° λλ€λ©΄ μμ νκ² μ΅λλ€.
ν΄λΉ μμ λ λ©μ΄λΈ νλ‘μ νΈλ‘ ꡬμ±λμ΄ μμΌλ©°, JUnit testμ μ¬μ μ μλ Functional interfaceμ Collections, Stream API κ° ν¬ν¨λμ΄ μλ€.