μλ°μ μ μ 14μ₯: λλ€μ μ€νΈλ¦Ό(Lamda & Stream)
[ μΆμ² ]
μλ°μ μ μ:
https://product.kyobobook.co.kr/detail/S000001550352
μλ°μ μ μ μ νλΈ:
https://www.youtube.com/playlist?list=PLW2UjW795-f6xWA2_MUhEVgPauhGl3xIp

14-1 λλ€μ(Lambda Expression )
- ν¨μ(λ©μλ)λ₯Ό κ°λ¨ν βμ(expression)βμΌλ‘ νννλ λ°©λ²μ΄λ€.
int max(int a, int b) { // λ©μλ return a > b ? a : b; }
(a, b) -> a > b ? a : b // λλ€μ
- μ΅λͺ
ν¨μ(μ΄λ¦μ΄ μλ ν¨μ, anonymous)
λ©μλλ₯Ό λλ€μμΌλ‘ νννλ©΄ λ©μλμ μ΄λ¦κ³Ό λ°νκ°μ΄ μμ΄μ§λ―λ‘ μ΅λͺ ν¨μλΌκ³ νλ€.
int max(int a, int b) { // λ©μλ return a > b ? a : b; }
int max(int a, int b) -> { // λλ€μ return a > b ? a : b; }
- ν¨μμ λ©μλμ μ°¨μ΄
- 근볡μ μΌλ‘ λμΌ. ν¨μλ μΌλ°μ μ©μ΄, λ©μλλ κ°μ²΄μ§ν₯κ°λ μ©μ΄
- ν¨μλ ν΄λμ€μ λ 립μ , λ©μλλ ν΄λμ€μ μ’ μμ
Javaλ μλ OOPμΈμ΄μ
JDK1.8λΆν° ν¨μν μΈμ΄μ κΈ°λ₯μ ν¬ν¨μν΄
oopμ ν¨μνμΈμ΄λΌκ³ ν μλ μμΌλ ν¨μνμΈμ΄λΌκ³ νκΈ°μλ κΈ°λ₯μ΄ μ’ μ½ν¨ κ·Έλ₯ ν¨μν μΈμ΄μ κΈ°λ₯μ ν¬ν¨νκ³ μλ€ μ λλ‘ μκ³ μμΌλ©΄ λ¨
python, js β λλ€ oop, fp
μ 리 : λλ€μμ ν¨μ(λ©μλ)λ₯Ό κ°λ¨ν νννλ €κ³ μ°λ κ²μ΄λ€.
14-2 λλ€μ μμ±νκΈ°
λλ€μ μμ±νκΈ°
- λ©μλμ μ΄λ¦κ³Ό λ°ννμ
μ μ κ±°νκ³ , λ§€κ°λ³μ μ μΈλΆμ λͺΈν΅{} μ¬μ΄μ βββλ₯Ό μΆκ°νλ€.
int max(int a, int b) { // λ©μλ return a > b ? a : b; }
int max(int a, int b) -> { // λλ€μ return a > b ? a : b; }
- λ°νκ°μ΄ μλ κ²½μ°, μμ΄λ κ°λ§ μ κ³ returnλ¬Έ μλ΅ κ°λ₯(λμ β;β μ λΆμ)
(int a, int b) -> { return a > b ? a : b; }
(int a, int b) -> a > b ? a : b
- λ§€κ°λ³μμ νμ
μ΄ μΆλ‘ κ°λ₯νλ©΄ μλ΅κ°λ₯(λλΆλΆμ κ²½μ° μλ΅κ°λ₯)
(int a, int b) -> a > b ? a : b
(a, b) -> a > b ? a : b
μ£Όμμ¬ν
- λ§€κ°λ³μκ° νλμΈ κ²½μ°, κ΄νΈ() μλ΅κ°λ₯(νμ
μ΄ μμ λλ§)
(a) -> a * a (int a) -> a * a
a -> a * a // OK int a -> a * a // μλ¬
- λΈλ‘ μμ λ¬Έμ₯μ΄ νλλΏμΌ λ, κ΄νΈ{} μλ΅κ°λ₯(λμ β;β μ λΆμ)
(int i) -> { System.out.println(i); }
(int i) -> System.out.println(i);
λ¨, νλλΏμΈ λ¬Έμ₯μ΄ returnλ¬Έμ΄λ©΄ κ΄νΈ{} μλ΅λΆκ°
(int a, int b) -> { return a > b ? a : b; } // OK (int a, int b) -> return a > b ? a : b // μλ¬
λλ€μ μμ±νκΈ° ν΄μ¦
λ©μλ | λλ€μ |
---|---|
int max(int a, int b) { return a > b ? a : b } | (a, b) β a > b ? a : b |
int printVar(String name, int i) { System.out.println(name + β=β + i); } | (name, i) β System.out.println(name + β=β + i) |
int square(int x) { return x * x; } | x β x * x |
int roll() { return (int) (Math.random() * 6); } | () β (int) (Math.random() * 6) |
14-4 λλ€μμ μ΅λͺ ν¨μ? μ΅λͺ κ°μ²΄!
- λλ€μμ μ΅λͺ
ν¨μκ° μλλΌ μ΅λͺ
κ°μ²΄μ΄λ€.
μλ°μμλ λ©μλλ§ μ‘΄μ¬ν μ μκΈ° λλ¬Έμ(λ°λμ ν΄λμ€ μμ μν΄μΌ ν¨)
(a, b) -> a > b ? a : b
λλ€μ == κ°μ²΄
new Object() { int max(int a, int b) { return a > b ? a : b; } }
κ°μ²΄μ μ μΈκ³Ό μμ±μ λμμ ν κ²μ΄λ€.
- λλ€μ(μ΅λͺ
κ°μ²΄)μ λ€λ£¨κΈ° μν μ°Έμ‘°λ³μκ° νμ. μ°Έμ‘°λ³μμ νμ
μ?
κ°μ²΄λ₯Ό λ€λ£¨κΈ° μν΄μ μ°Έμ‘°λ³μκ° νμνλ€.
Object obj = new Object() { int max(int a, int b) { return a > b ? a : b; } }
νμ obj = (a, b) -> a > b ? a : b; // μ΄λ€ νμ ?
int value = obj.max(3, 5); // μλ¬. Object ν΄λμ€μ max()κ° μμ
ObjectλΌλ 리λͺ¨μ»¨μμλ max()κ° μλ€.
κ·Έλ¬λ©΄, μ°Έμ‘°λ³μ fμ νμ μ μ΄λ€ κ²μ΄μ΄μΌ ν κΉ? μ°Έμ‘°νμ΄λκΉ ν΄λμ€ λλ μΈν°νμ΄μ€κ° κ°λ₯νλ€. κ·Έλ¦¬κ³ λλ€μκ³Ό λλ±ν λ©μλκ° μ μλμ΄ μλ κ²μ΄μ΄μΌ νλ€. κ·ΈλμΌ μ°Έμ‘°λ³μλ‘ μ΅λͺ κ°μ²΄(λλ€μ)μ λ©μλλ₯Ό νΈμΆν μ μκΈ° λλ¬Έμ΄λ€.
14-0 μμ
package Test; class Main { public static void main(String args[]) { // The target type of this expression must be a functional interfaceJava(553648781) // λλ€μμ ν¨μν μΈν°νμ΄μ€λ‘ λ€λ€μΌ νλ€λ μλ¬ λ©μμ§κ° λμ¨λ€. // Object obj = (a, b) -> a > b ? a : b ;// λλ€μ. μ΅λͺ κ°μ²΄ / κ°μ²΄μ΄κΈ° λλ¬Έμ μ°Έμ‘°λ³μλ‘ λ€λ€μΌ νλ€. Object obj = new Object() { int max(int a, int b) { return a > b ? a : b; } }; int value = obj.max(3, 5); // Obejct typeμ 리λͺ¨μ»¨μλ max λ©μλκ° μ‘΄μ¬νμ§ μμ -> ν¨μν μΈν°νμ΄μ€κ° νμ } // main }
14-5 ν¨μν μΈν°νμ΄μ€
- ν¨μν μΈν°νμ΄μ€ - λ¨ νλμ μΆμ λ©μλλ§ μ μΈλ μΈν°νμ΄μ€
λλ€μμ λ€λ£¨κΈ° μν μΈν°νμ΄μ€μ΄λ€.
// ν¨μν μΈν°νμ΄μ€λ₯Ό μ¬λ°λ₯΄κ² μμ±νλμ§ νμΈν΄μ€λ€. / νμλ μλ, λΆμ΄λ©΄ μ’λ€λ κ² @FunctionalInterface interface MyFunction { public abstract int max(int a, int b); }
MyFunction f = new MyFunction() { // μ΅λͺ ν΄λμ€μ μ μΈ, κ°μ²΄ μμ± λμμ public int max(int a, int b) { return a > b ? a : b; } }
new μ‘°μμ΄λ¦(ν΄λμ€ or μΈν°νμ΄μ€) { // λ©€λ² }
int value = f.max(3, 5); // OK. MyFunctioinμ max()κ° μμ
- ν¨μν μΈν°νμ΄μ€ νμ
μ μ°Έμ‘°λ³μλ‘ λλ€μμ μ°Έμ‘°ν μ μμ.
(λ¨, ν¨μν μΈν°νμ΄μ€μ λ©μλμ λλ€μμ
λ§€κ°λ³μ κ°μμ λ°ννμ μ΄ μΌμΉν΄μΌ ν¨)MyFunction f = (a, b) -> a > b > a : b; int value = f.max(3, 5); // μ€μ λ‘λ λλ€μ(μ΅λͺ ν¨μ)μ΄ νΈμΆλ¨
- ν¨μν μΈν°νμ΄μ€ μμ
class Main { public static void main(String args[]) { // MyFunction f = new MyFunction() { // // int max(int a, int b) { // μ€λ²λΌμ΄λ© κ·μΉ : μ‘°μ λ©μλλ³΄λ€ μ’κ·Ό μ κ·Όμ μ΄μλ₯Ό κ°μ§ μ μμ. // public int max(int a, int b) { // return a > b ? a : b; // } // }; // λλ€μ(μ΅λͺ κ°μ²΄)μ λ€λ£¨κΈ° μν μ°Έμ‘°λ³μμ νμ μ ν¨μν μΈν°νμ΄μ€λ‘ νλ€. MyFunction f = (a, b) -> a > b ? a : b; // λλ€μ int value = f.max(3, 5); // ν¨μν μΈν°νμ΄μ€ System.out.println(value); } // main } @FunctionalInterface // ν¨μν μΈν°νμ΄μ€λ λ¨ νλμ μΆμ λ©μλλ§ κ°μ ΈμΌ νλ€. interface MyFunction { int max(int a, int b); // μΈν°νμ΄μ€μ λͺ¨λ λ©μλλ publicμ΄λ©΄μ abstractλ€. μλ΅ κ°λ₯. // public abstract int max(int a, int b); // public abstract int max(int a, int b); // FunctionalInterface μ λν μ΄μ μ λΆμμ κ²½μ° ν¨μν μΈν°νμ΄μ€λ₯Ό μ¬λ°λ₯΄κ² μμ±νλμ§ νμΈν΄μ€λ€. }
class Main { public static void main(String args[]) { // λλ€μ(μ΅λͺ κ°μ²΄)μ λ€λ£¨κΈ° μν μ°Έμ‘°λ³μμ νμ μ ν¨μν μΈν°νμ΄μ€λ‘ νλ€. MyFunction f = (a, b) -> a > b ? a : b; // λλ€μ int value = f.max(3, 5); // ν¨μν μΈν°νμ΄μ€ System.out.println(value); } // main } @FunctionalInterface // ν¨μν μΈν°νμ΄μ€λ λ¨ νλμ μΆμ λ©μλλ§ κ°μ ΈμΌ νλ€. interface MyFunction { int max(int a, int b); // μΈν°νμ΄μ€μ λͺ¨λ λ©μλλ publicμ΄λ©΄μ abstractλ€. μλ΅ κ°λ₯. }
- λ³ν κ³Όμ (23.04.03. μΆκ°)
public class Main2 { public static void main(String[] args) { MyFunction f = new Test(); } } interface MyFunction { int max(int a, int b); } class Test implements MyFunction { @Override public int max(int a, int b) { return a > b ? a : b; } }
public class Main2 { public static void main(String[] args) { MyFunction f = new MyFunction() { @Override public int max(int a, int b) { return a > b ? a : b; } }; } } interface MyFunction { int max(int a, int b); }
public class Main2 { public static void main(String[] args) { MyFunction f1 = (a, b) -> a > b ? a : b; } } interface MyFunction { int max(int a, int b); }
14-5 ν¨μν μΈν°νμ΄μ€ - example
- μ΅λͺ
κ°μ²΄λ₯Ό λλ€μμΌλ‘ λ체
List<String> list = Arrays.asList("abc", "aaa", "bbb", "ddd", "aaa"); Collections.sort(list, new Comparator<String>() { public int compare(String s1, String s2) { return s2.compareTo(s1); } });
β¬
@FunctionalInterface // ν¨μν μΈν°νμ΄μ€ interface Comparator<T> { int compare(T o1, T o2); }
List<String> list = Arrays.asList("abc", "aaa", "bbb", "ddd", "aaa"); Collections.sort(list, (s1, s2) -> s2.compareTo(s1));
- λ³ν κ³Όμ (23.04.03. μΆκ°)
public class Main2 { public static void main(String[] args) { List<String> list = Arrays.asList("abc", "aaa", "bbb", "ddd", "aaa"); Collections.sort(list, new SortTest()); } } class SortTest implements Comparator<String> { @Override public int compare(String o1, String o2) { return o2.compareTo(o1); // μ λ ¬κΈ°μ€ μ 곡 } }
public class Main2 { public static void main(String[] args) { List<String> list = Arrays.asList("abc", "aaa", "bbb", "ddd", "aaa"); Collections.sort(list, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o2.compareTo(o1); } }); } }
public class Main2 { public static void main(String[] args) { List<String> list = Arrays.asList("abc", "aaa", "bbb", "ddd", "aaa"); Collections.sort(list, (o1, o2) -> o2.compareTo(o1)); } }
14-6 ν¨μν μΈν°νμ΄μ€ νμ μ λ§€κ°λ³μ, λ°ννμ
- ν¨μν μΈν°νμ΄μ€ νμ
μ λ§€κ°λ³μ β λλ€μμ λ§€κ°λ³μλ‘ λ°κ² λ€λ λ»μ΄λ€.
void aMethod(MyFunction f) { // λλ€μμ λ§€κ°λ³μλ‘ λ°κ² λ€λ λ»μ΄λ€. f.myMethod(); // MyFunctionμ μ μλ λ©μλ νΈμΆ }
MyFunction f = () -> System.out.println("test"); aMethod(f); // aMethod(() -> System.out.println("test"));
interface MyFunction { void myMethod(); }
- ν¨μν μΈν°νμ΄μ€ νμ
μ λ°ννμ
β λλ€μμ λ°ννλΌλ λ»
MyFunction myMethod() { // λλ€μ λ°ν MyFunction f = () -> {}: return f; }
β©
MyFunction myMethod() { return () -> {}; }
μμ 14-1
package Test; @FunctionalInterface interface MyFunction { void run(); // public abstract void run(); } class Main { static void execute(MyFunction f) { // λ§€κ°λ³μμ νμ μ΄ MyFunctionμΈ λ©μλ f.run(); } static MyFunction getMyFunction() { // λ°ν νμ μ΄ MyFunctionμΈ λ©μλ return () -> System.out.println("f3.run()"); } public static void main(String args[]) { MyFunction f1 = () -> System.out.println("f1.run()"); MyFunction f2 = new MyFunction() { public void run() { // publicμ λ°λμ λΆμ¬μΌ ν¨ System.out.println("f2.run()"); } }; MyFunction f3 = getMyFunction(); // MyFunction f3 = () -> System.out.println("f3.run()"); // μμ λμΌ f1.run(); f2.run(); f3.run(); System.out.println("======= execute ========="); execute(f1); execute(f2); execute(f3); execute(() -> System.out.println("run()")); } // main }
μμ 14-1 λ³νκ³Όμ (23.04.03. μ μΆκ°)
@FunctionalInterface interface MyFunction { void run(); // public abstract μλ΅ } class Test implements MyFunction { @Override public void run() { System.out.println("f1.run"); } } public class Main2 { public static void main(String[] args) { MyFunction f1 = new Test(); f1.run(); } }
@FunctionalInterface interface MyFunction { void run(); // public abstract μλ΅ } public class Main2 { public static void main(String[] args) { MyFunction f1 = new MyFunction() { @Override public void run() { System.out.println("f1.run"); } }; f1.run(); } }
@FunctionalInterface interface MyFunction { void run(); // public abstract μλ΅ } public class Main2 { public static void main(String[] args) { MyFunction f1 = () -> System.out.println("f1.run"); f1.run(); } }
14-7 java.util.function ν¨ν€μ§
- μμ£Ό μ¬μ©λλ λ€μν ν¨μν μΈν°νμ΄μ€λ₯Ό μ 곡
ν¨μν μΈν°νμ΄μ€
ν¨μν μΈν°νμ΄μ€ | λ©μλ | μ€λͺ |
---|---|---|
java.lang.Runnable | void run() | λ§€κ°λ³μλ μκ³ , λ°νκ°λ μμ |
Supplier<T> | T get() | λ§€κ°λ³μλ μκ³ , λ°νκ°λ§ μμ |
Consumer<T> | void accept(T t) | Supplierμ λ°λλ‘ λ§€κ°λ³μλ§ μκ³ , λ°νκ°μ΄ μμ |
Function<T,R> | R apply(T t) | μΌλ°μ μΈ ν¨μ, νλμ λ§€κ°λ³μλ₯Ό λ°μμ κ²°κ³Όλ₯Ό λ°ν |
Predicate<T> | boolean test(T t) | 쑰건μμ νννλλ° μ¬μ©λ¨. λ§€κ°λ³μλ νλ, λ°ν νμ μ boolean |
Predicate<String> isEmptyStr = s -> s.length() == 0;
String s = "";
if (isEmptyStr.test(s)) { // if(s.length() == 0)
System.out.println("This is an empty String.");
}
- Q. μλμ λΉ μΉΈμ μλ§μ ν¨μν μΈν°νμ΄μ€(java.util.function ν¨ν€μ§)λ₯Ό μ μΌμμ€.
[ β ] f = () -> (int)(Math.random() * 100) + 1; [ β‘ ] f = i -> System.out.print(i + ", "); [ β’ ] f = i -> i%2 == 0; [ β£ ] f = i -> i/10*10;
μ λ΅
Supplier<Interger> f = () -> (int)(Math.random() * 100) + 1; // input x output O Consumer<Integer> f = i -> System.out.print(i + ", "); Predicate<Integer> f = i -> i%2 == 0; Function<Integer, Integer> f = i -> i/10*10;
λ§€κ°λ³μκ° 2κ°μΈ ν¨μν μΈν°νμ΄μ€
ν¨μν μΈν°νμ΄μ€ | λ©μλ | μ€λͺ |
---|---|---|
BiConsumer<T,U> | void accept(T t, U u) | λκ°μ λ§€κ°λ³μλ§ μκ³ , λ°νκ°μ΄ μμ |
BiPredicate<T,U> | boolean test(T t, U u) | 쑰건μμ νννλλ° μ¬μ©λ¨. λ§€κ°λ³μλ λ, λ°νκ°μ boolean |
BiFunction<T,U,R> | R apply(T t, U u) | λ κ°μ λ§€κ°λ³μλ₯Ό λ°μμ νλμ κ²°κ³Όλ₯Ό λ°ν |
@FunctionalInterface
interface TriFunction<T,U,V,R> {
R apply(T t, U u, V v);
}
λ§€κ°λ³μμ νμ κ³Ό λ°ννμ μ΄ μΌμΉνλ ν¨μν μΈν°νμ΄μ€
ν¨μν μΈν°νμ΄μ€ | λ§€μλ | μ€λͺ |
---|---|---|
UnaryOperator<T> | T apply(T t) | Functionμ μμ, Functionκ³Ό λ¬λ¦¬ λ§€κ°λ³μμ κ²°κ³Όμ νμ μ΄ κ°λ€. |
BinaryOperator<T> | T apply(T t, T t) | BiFunctionμ μμ, BiFunctionκ³Ό λ¬λ¦¬ λ§€κ°λ³μμ κ²°κ³Όμ νμ μ΄ κ°λ€. |
Unary : λ¨ν
Binary : μ΄ν
Operator : μ°μ°μ
μμ 14-2
package Test; import java.util.ArrayList; import java.util.List; import java.util.function.*; class Main { public static void main(String args[]) { Supplier<Integer> s = () -> (int)(Math.random() * 100) + 1; Consumer<Integer> c = i -> System.out.print(i + ", "); Predicate<Integer> p = i -> i % 2 == 0; Function<Integer, Integer> f = i -> i / 10 * 10; List<Integer> list = new ArrayList<>(); makeRandomList(s, list); // 1~100 λ²μμ λλ€κ°μ Listμ 10κ° λ£λλ€. System.out.println(list); printEvenNum(p, c, list); List<Integer> newList = doSomething(f, list); System.out.println(newList); } // main static <T> List<T> doSomething(Function<T, T> f, List<T> list) { List<T> newList = new ArrayList<T>(list.size()); for (T i : list) { newList.add(f.apply(i)); } return newList; } static <T> void printEvenNum(Predicate<T> p, Consumer<T> c, List<T> list) { System.out.print("["); for (T i : list) { // listμ μλ κ°μ νλμ© κ°μ Έμ¨λ€. if (p.test(i)) { // iμ κ°μ΄ μ§μλ©΄ c.accept(i); // iμ κ°μ μΆλ ₯νλ€. } } System.out.println("]"); } static <T> void makeRandomList(Supplier<T> s, List<T> list) { for (int i = 0; i < 10; i++) { list.add(s.get()); // 1~100 λ²μμ λλ€κ°μ Listμ 10κ° λ£λλ€. } } }
14-8 Predicateμ κ²°ν©
- and(), or(), negate()λ‘ λ Predicateλ₯Ό νλλ‘ κ²°ν©(default λ©μλ)
μΈν°νμ΄μ€ = μΆμλ©μλ, static λ©μλ, default λ©μλ
Predicate<Integer> p = i -> i < 100; Predicate<Integer> q = i -> i < 200; Predicate<Integer> r = i -> i % 2 == 0;
Predicate<Integer> notP = p.negate(); // i >= 100 Predicate<Integer> all = notP.and(q).or(r); // 100 <= i && i < 200 || i % 2 == 0 Predicate<Integer> all2 = notP.and(q.or(r)); // 100 <= i && (i < 200 || i % 2 == 0)
System.out.println(all.test(2)); // true System.out.println(all2.test(2)); // false
- λ±κ°λΉκ΅λ₯Ό μν Predicateμ μμ±μλ isEqual()λ₯Ό μ¬μ©(staticλ©μλ)
Predicate<String> p = Predicate.isEqual(str1); // isEqual()λ staticλ©μλ Boolean result = p.test(str2); // str1κ³Ό str2κ° κ°μμ§ λΉκ΅ν κ²°κ³Όλ₯Ό λ°ν -> boolean result = Predicate.isEqual(str1).test(str2);
μμ 14-3
// "abc" == "abc" -> true // new String("abc") == "abc" -> false(μ£Όμ λΉκ΅μ΄κΈ° λλ¬Έμ΄λ€.) String str1 = new String("abc"); String str2 = new String("abc"); System.out.println(str1 == str2); // μ΄ κ²°κ³Όκ°μ΄ trueλΌλ 건 λ±κ°λΉκ΅κ° μλλΌ equalsλ₯Ό μΌλ€λ κ±Έ μ μ μλ€. boolean result = Predicate.isEqual(str1).test(str2); System.out.println(result);
package chapter14; import java.util.function.Function; import java.util.function.Predicate; class Ex14_3 { public static void main(String args[]) { Function<String, Integer> f = (s) -> Integer.parseInt(s, 16); // 16μ§μλ₯Ό 10μ§μλ‘ λ³ν Function<Integer, String> g = (i) -> Integer.toBinaryString(i); Function<String, String> h = f.andThen(g); // f μ μ©νκ³ gλ₯Ό μ μ©ν΄λΌ Function<Integer, Integer> h2 = f.compose(g); // g μ μ©νκ³ fλ₯Ό μ μ©ν΄λΌ System.out.println(h.apply("FF")); // "FF" -> 255 -> "11111111" System.out.println(h2.apply(2)); // 2 -> "10" -> 16 Function<String, String> f2 = x -> x; // νλ± ν¨μ(identity function) System.out.println(f2.apply("AAA")); // AAAκ° κ·Έλλ‘ μΆλ ₯λ¨ Predicate<Integer> p = i -> i < 100; Predicate<Integer> q = i -> i < 200; Predicate<Integer> r = i -> i % 2 == 0; Predicate<Integer> notP = p.negate(); // negate == not / i >= 100 Predicate<Integer> all = notP.and(q.or(r)); // i >= 100 && (i < 200 || i % 2 == 0) System.out.println(notP.test(150)); // true String str1 = "abc"; String str2 = "abc"; // Predicate<String> p2 = Predicate.isEqual(str1); // isEqualμ λ°ννμ μ Predicate(λλ€μ λ°ν) // boolean result = p2.test(str2); System.out.println(Predicate.isEqual(str1).test(str2)); } // main }
14-11 컬λ μ νλ μμκ³Ό ν¨μν μΈν°νμ΄μ€
- ν¨μν μΈν°νμ΄μ€λ₯Ό μ¬μ©νλ 컬λ μ
νλ μμν¬μ λν΄νΈ λ©μλ(μμΌλ μΉ΄λ μλ΅)π‘λ©μλ μ°Έμ‘° == ν΄λμ€μ΄λ¦::λ©μλμ΄λ¦
λ©μλ μ°Έμ‘°λ λλ€μμ λ κ°λ¨ν ν κ²μ΄λ€.
μΈν°νμ΄μ€ | λ©μλ | μ€λͺ |
---|---|---|
Collection | boolean removeIf(Predicate<E> filter) | 쑰건μ λ§λ μμλ₯Ό μμ |
List | void replaceAll(UnaryOperator<E> operator | λͺ¨λ μμλ₯Ό λ³ννμ¬ λ체 |
Iterable | void forEach(Consumer<T> action) | λͺ¨λ μμμ μμ actionμ μν |
Map | V compute(K key, BiFunction<K,V,V> f) | μ§μ λ ν€μ κ°μ μμ fλ₯Ό μν |
ββ | V computeIfAbsent(K key, Function<K,V> f) | ν€κ° μμΌλ©΄, μμ f μν ν μΆκ° |
ββ | V computeIfPresent(K key, BiFunction<K,V,V> f) | μ§μ λ ν€κ° μμ λ, μμ f μν |
ββ | V merge(K key, V value, BiFunction<V,V,V> f) | λͺ¨λ μμμ λ³ν©μμ fλ₯Ό μν |
ββ | void forEach(BiConsumer<K,V> action) | λͺ¨λ μμμ μμ actionμ μν |
ββ | void replaceAll(BiFunction<K,V,V> f) | λͺ¨λ μμμ μΉνμμ fλ₯Ό μν |
compute β mapμ valueλ₯Ό λ³ν
μμ 14-4
package Test; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; class Main { public static void main(String args[]) { ArrayList<Integer> list = new ArrayList<>(); for (int i = 0; i < 10; i++) { list.add(i); } // Iterator it = list.iterator(); // while (it.hasNext()) { // System.out.println(it.next()); // } list.forEach(i -> System.out.print(i + ",")); System.out.println(); list.removeIf(x -> x % 2 == 0 || x % 3 == 0); // listμμ 2λλ 3μ λ°°μλ₯Ό μ κ±°νλ€. System.out.println(list); list.replaceAll(i -> i * 10); // listμ κ° μμμ 10μ κ³±νλ€. System.out.println(list); Map<String, String> map = new HashMap<>(); map.put("1", "1"); map.put("2", "2"); map.put("3", "3"); map.put("4", "4"); // Iterator it = map.entrySet().iterator(); // while (it.hasNext()) { // System.out.println(it.next()); // } // mapμ λͺ¨λ μμλ₯Ό {k, v}μ νμμΌλ‘ μΆλ ₯νλ€. map.forEach((k, v) -> System.out.printf("{%s, %s}, ", k, v)); } // main }
14-13 λ©μλ μ°Έμ‘°(method reference)
- νλμ λ©μλλ§ νΈμΆνλ λλ€μμ βλ©μλ μ°Έμ‘°βλ‘ λ κ°λ¨ν ν μ μλ€.
β λ©μλ μ°Έμ‘° == λλ€μμ λ κ°λ¨ν ν κ²
μ’ λ₯ λλ€ λ©μλ μ°Έμ‘° static λ©μλ μ°Έμ‘° (x) β ClassName.method(x) ClassName::method μΈμ€ν΄μ€ λ©μλ μ°Έμ‘° (obj, x) β obj.method(x) ClassName::method νΉμ κ°μ²΄ μΈμ€ν΄μ€ λ©μλ μ°Έμ‘°(x) β obj.method(x)obj::method
- static λ©μλ μ°Έμ‘°
βΌ
βΌ
// κ·Έμ Integer.parseInt(String s) λ§ νΈμΆ
Integer method(String s) {
return Integer.parseInt(s);
}
int result = obj.method("123");
int result = Integer.parseInt("123");
Function<String, Integer> f
= (String s) -> Integer.parseInt(s); // λλ€μ
// ν¨μν μΈν°νμ΄μ€μ μ λ³΄κ° λ€ μκΈ° λλ¬Έμ μ§μΈ μ μμ
Function<String, Integer> f = Integer::parseInt; // λ©μλ μ°Έμ‘°
μμ
Function<String, Integer> f = s -> Integer.parseInt(s); // λλ€μ Function<String, Integer> f2 = Integer::parseInt; // λ©μλ μ°Έμ‘°, μ λ ₯μ΄ String μ΄λΌλ 건 ν¨μν μΈν°νμ΄μ€μ μ λ³΄κ° λ€ μκΈ° λλ¬Έμ μ μΈ μ μλ€. System.out.println(f.apply("100") + 200); System.out.println(f2.apply("300") + 100); // λ©μλ μ°Έμ‘° -> λλ€μ // 1. μ λ ₯μ μ΄λ€. // 2. "::" -> "." // 3. λ§€κ°λ³μλ₯Ό λ£μ΄μ€λ€. Function<String, Integer> f3 = (s) -> Integer.parseInt(s);
14-14 μμ±μμ λ©μλ μ°Έμ‘°
- μμ±μμ λ©μλ μ°Έμ‘°
Supplier<MyClass> s = () -> new MyClass();
βΆοΈ
Supplier<MyClass> s = MyClass::new;
μμ±μμ λ§€κ°λ³μκ° μλ κ²½μ°
Function<Integer, MyClass> s = i -> new MyClass(i);
βΆοΈ
Function<Integer, MyClass> s = MyClass:new;
- λ°°μ΄κ³Ό λ©μλ μ°Έμ‘°
Function<Integer, int[]> f = x -> new int[x]; // λλ€μ Function<Integer, int[]> f = int[]::new; // λ©μλμ°Έμ‘° - μ΄κ±° λ§μ΄ μ΄λ€κ³ ν¨
μμ
Supplier<MyClass> s = () -> new MyClass(); // λλ€μ Supplier<MyClass> s2 = MyClass::new; // λ©μλ μ°Έμ‘° MyClass mc = s.get(); System.out.println(mc); Function<Integer, MyClass> f = i -> new MyClass(i); Function<Integer, MyClass> f2 = MyClass::new; System.out.println(f2.apply(100).iv); BiFunction<Integer, String, MyClass> b = (i, str) -> new MyClass(i, str); BiFunction<Integer, String, MyClass> b2 = MyClass::new; System.out.println(b2.apply(21, "λ°©μ±λ―Ό").str); Function<Integer, int[]> f3 = i -> new int[i]; // λλ€μ Function<Integer, int[]> f4 = int[]::new; // λ©μλ μ°Έμ‘° int[] arr = f4.apply(99); System.out.println("arr.length = " + arr.length);
14-15 μ€νΈλ¦Ό(Stream)
- λ€μν λ°μ΄ν° μμ€λ₯Ό νμ€νλ λ°©λ²μΌλ‘ λ€λ£¨κΈ° μν κ²
μ€νΈλ¦Ό : λ°μ΄ν°μ μ°μμ μΈ νλ¦

<μ€νΈλ¦Ό μμ 3λ¨κ³>
- μ€νΈλ¦Ό λ§λ€κΈ°
- μ€κ° μ°μ°(0~nλ²)
- μ΅μ’ μ°μ°(0~1λ²)
- μ€νΈλ¦Όμ΄ μ 곡νλ κΈ°λ₯ - μ€κ° μ°μ°κ³Ό μ΅μ’
μ°μ°π‘μ€κ° μ°μ° - μ°μ° κ²°κ³Όκ° μ€νΈλ¦ΌμΈ μ°μ°. λ°λ³΅μ μΌλ‘ μ μ© κ°λ₯
μ΅μ’ μ°μ° - μ°μ° κ²°κ³Όκ° μ€νΈλ¦Όμ΄ μλ μ°μ°. λ¨ ν λ²λ§ μ μ©κ°λ₯(μ€νΈλ¦Όμ μμλ₯Ό μλͺ¨)
14-17~22 μ€νΈλ¦Ό λ§λ€κΈ°
컬λ μ
Collection μΈν°νμ΄μ€μ stream()μΌλ‘ 컬λ μ μ μ€νΈλ¦ΌμΌλ‘ λ³κ²½
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
Stream<Integer> intStream = list.stream(); // listλ₯Ό streamμΌλ‘ λ³ν(listλ₯Ό λ°μ΄ν° μμ€λ‘ νλ μλ‘μ΄ μ€νΈλ¦Όμ μμ±)
// streamμ 1νμ©. streamμ λν΄ μ΅μ’
μ°μ°μ μννλ©΄ streamμ΄ λ«νλ€.
intStream.forEach(System.out::print); // λ©μλ μ°Έμ‘°, 12345
intStream.forEach(System.out::print); // μλ¬. μ€νΈλ¦Όμ΄ μ΄λ―Έ λ«νλ€.
λ°°μ΄
- κ°μ²΄ λ°°μ΄λ‘λΆν° μ€νΈλ¦Ό μμ±νκΈ°
Stream<T> Stream.of(T... values) // κ°λ³μΈμ Stream<T> Stream.of(T[]) Stream<T> Arrays.stream(T[]) Stream<T> Arrays.stream(T[] array, int startInclusive, int endExclusive) Stream<String> strStream = Stream.of("a", "b", "c"); Stream<String> strStream = Stream.of(new String[] {"a", "b", "c"}); Stream<String> strStream = Arrays.stream(new String[] {"a", "b", "c"}); Stream<String> strStream = Arrays.stream(new String[] {"a", "b", "c"}, 0, 3);
- κΈ°λ³Έν λ°°μ΄λ‘λΆν° μ€νΈλ¦Ό μμ±νκΈ°
IntStream IntStream.of(int... values) // Streamμ΄ μλλΌ IntStream IntStream IntStream.of(int[]) IntStream Arrays.stream(int[]) IntStream Arrays.stream(int[] array, int startInclusive, int endExclusive)
String[] strArr = {"a", "b", "c", "d"};
// Stream<String> strStream = Stream.of(strArr);
Stream<String> strStream = Arrays.stream(strArr);
strStream.forEach(System.out::print);
int[] intArr = {1, 2, 3, 4, 5};
IntStream intStream = Arrays.stream(intArr);
System.out.println(intStream.sum()); // count(), average() - μ΅μ’
μ°μ°
,
Integer[] intArr = {new Integer(1), 2, 3, 4, 5};
Stream<Integer> intStream = Arrays.stream(intArr);
// κ°μ²΄ μ€νΈλ¦Όμ count()λ°μ μμ
// μ«μ μΈμλ μ¬λ¬ νμ
μ μ€νΈλ¦Όμ΄ κ°λ₯ν΄μΌνλ―λ‘ μ«μ μ€νΈλ¦Όμλ§ μ¬μ©ν μ μλ sum(), average()λ₯Ό λ£μ§ μμ κ²
System.out.println(intStream.count());
κΈ°λ³Έν λ°°μ΄μΌ λλ IntStream μ¨μ£Όλ κ² μ’λ€.
μμμ μ
- λμλ₯Ό μμλ‘ κ°λ μ€νΈλ¦Ό μμ±νκΈ°
IntStream intStream = new Random().inits(); // 무ν μ€νΈλ¦Ό intStream.limit(5).forEach(System.out::println); // 5κ°μ μμλ§ μΆλ ₯νλ€. IntStream intStream = new Random().ints(5); // ν¬κΈ°κ° 5μΈ λμ μ€νΈλ¦Όμ λ°ν
- μ§μ λ λ²μμ λμλ₯Ό μμλ‘ κ°λ μ€νΈλ¦Όμ μμ±νλ λ©μλ(Random ν΄λμ€)
IntStream ints(int begin, int end) // 무ν μ€νΈλ¦Ό LongStream longs(long begin, long end) DoubleStream doubles(double begin, double end) IntStream ints(long, streamSize, int begin, int end) // μ ν μ€νΈλ¦Ό LongStream longs(long, streamSize, long begin, long end) DoulbeStream longs(long, streamSize, double begin, double end)
μμ ?
// IntStream intStream = new Random().ints(); // 무ν μ€νΈλ¦Ό // IntStream intStream = new Random().ints(5); // μ ν μ€νΈλ¦Ό IntStream intStream = new Random().ints(5, 100); // 무ν μ€νΈλ¦Ό intStream .limit(10) // 5κ°λ§ μλ₯΄κΈ° .forEach(System.out::println);
μ€νΈλ¦Ό λ§λ€κΈ° - νΉμ λ²μμ μ μ
νΉμ λ²μμ μ μλ₯Ό μμλ‘ κ°λ μ€νΈλ¦Ό μμ±νκΈ°(IntStream, LongStream)
IntStream IntStream.rangeClosed(int begin, int end) // end ν¬ν¨
IntStream intStream = IntStream.range(1, 5);
IntStream intStream = IntStream.rangeClosed(1, 5);
μ€νΈλ¦Ό λ§λ€κΈ° - λλ€μ iterate(), generate()
- λλ€μμ μμ€λ‘ νλ μ€νΈλ¦Ό μμ±νκΈ°
static <T> Stream<T> iterate(T seed, UnaryOperator<T> f) // μ΄μ μμμ μ’ μμ static <T> Stream<T> generate(Supplier<T> s) // μ΄μ μμμ λ 립μ
- iterate()λ μ΄μ μμλ₯Ό seedλ‘ ν΄μ λ€μ μμλ₯Ό κ³μ°νλ€.
Stream<Integer> evenStream = Stream.iterator(0, n -> n + 2); // 0, 2, 4, 6 ... 무ν μ€νΈλ¦Ό
- generate()λ seedλ₯Ό μ¬μ©νμ§ μλλ€.
Stream<Double> randomStream = Stream.generate(Math::random); Stream<Double> oneStream = Stream.generate(() -> 1);
μ€νΈλ¦Ό λ§λ€κΈ° - νμΌκ³Ό λΉ μ€νΈλ¦Ό
- νμΌμ μμ€λ‘ νλ μ€νΈλ¦Ό μμ±νκΈ°
Stream<Path> Files.list(Path dir) // Pathλ νμΌ λλ λλ ν 리
Stream<String> Files.lines(Path path) Stream<String> Files.lines(Path path, Charset cs) Stream<String> lines() // BufferedReader ν΄λμ€μ λ©μλ
- λΉμ΄μλ μ€νΈλ¦Ό μμ±νκΈ°
Stream emptyStream = Stream.empty(); // empty()λ λΉ μ€νΈλ¦Όμ μμ±ν΄μ λ°ννλ€. long count = emptyStream.count(); // countμ κ°μ 0
14-23 μ€νΈλ¦Όμ μ°μ°
- μ€νΈλ¦Όμ΄ μ 곡νλ κΈ°λ₯ - μ€κ° μ°μ°κ³Ό μ΅μ’ μ°μ°
14-26~29 μ€νΈλ¦Όμ μ€κ°μ°μ°
μ€νΈλ¦Ό μλ₯΄κΈ° - skip(), limit()
Stream<T> skip(long n) // μμμλΆν° nκ° κ±΄λλ°κΈ°
Stream<T> limit(long maxSize() // maxSize μ΄νμ μμλ μλΌλ
IntStream intStream = IntStream.rangeClosed(1, 10); // 12345678910
intStream.skip(3).limit(5).forEach(System.out::print);; // 45678
μ€νΈλ¦Όμ μμ κ±Έλ¬λ΄κΈ° - filter(), distinct()
Stream<T> filter(Predicate<? super T> predicate) // 쑰건μ λ§μ§ μλ μμ μ κ±°
Stream<T> distinct() // μ€λ³΅μ κ±°
IntStream intStream = IntStream.of(1, 2, 2, 3, 3, 4, 5, 5, 6);
intStream.distinct().forEach(System.out::print); // 123456
IntStream intStream = IntStream.rangeClosed(1, 10); // 12345678910
intStream.filter(i -> i % 2 == 0).forEach(System.out::print);; // 246810 μ§μ κ°λ§ λ¨κΈ΄λ€.
// μ€κ°μ°μ°μ΄λΌ filter μ¬λ¬λ² μ¬μ© κ°λ₯
intStream.filter(i -> i % 2 != 0 && i % 3 != 0).forEach(System.out::print);
intStream.filter(i -> i % 2 != 0).filter(i -> i % 3 != 0).forEach(System.out::print);
μ€νΈλ¦Ό μ λ ¬νκΈ° - sorted()
Stream<T> sorted() // μ€νΈλ¦Ό μμμ κΈ°λ³Έ μ λ ¬(Comparable)λ‘ μ λ ¬
Stream<T> sorted(Comparator<? supter T> comparator) // μ§μ λ Comparatorλ‘ μ λ ¬
Comparatorμ comparing()μΌλ‘ μ λ ¬ κΈ°μ€μ μ 곡(λ°ννμ μ΄ comparatorμ)
comparing(Function<T,U> keyExtractor, Comparator<U> keyComparator)
studentStream.sorted(Comparator.comparing(Student::getBan)
.forEach(System.out::println);
μΆκ° μ λ ¬ κΈ°μ€μ μ 곡ν λλ thenComparing()μ μ¬μ©
thenComparing(Function<T,U> keyExtractor)
thenComparing(Function<T,U> keyExtractor, Comparator<U> keyComp)
studentStream.sorted(Comparator.comparing(Student::getBan) // λ°λ³λ‘ μ λ ¬
.thenComparing(Student::getTotalScore) // μ΄μ λ³λ‘ μ λ ¬
.thenComparing(Student::getName)) // μ΄λ¦λ³λ‘ μ λ ¬
.forEach(System.out::println);
μ€νΈλ¦Όμ μμ λ°ννκΈ° - map()
Stream<File> fileStream = Stream.of(new File("Ex1.java"), new File("Ex1.bak"),
new File("Ex2.java"), new File("Ex1"), new File("Ex1.txt")); // μμ file κ°μ²΄λ₯Ό streamμΌλ‘ λ§λ€μλ€.
Stream<String> fileNameStream = fileStream.map(File::getName);
fileNameStream.forEach(System.out::println); // μ€νΈλ¦Όμ λͺ¨λ νμΌμ μ΄λ¦μ μΆλ ₯

μμ ) νμΌ μ€νΈλ¦Ό(Stream<File>)μμ νμΌ νμ₯μ(λλ¬Έμ)λ₯Ό μ€λ³΅μμ΄ λ½μλ΄κΈ°
fileStream.map(File::getName) // Stream<FIle> -> Stream<String>
.filter(s -> s.indexOf(".") != -1) // νμ₯μκ° μλ κ²μ μ μΈ
.map(s -> s.substring(s.indexOf(".") + 1)) // νμ₯μλ§ μΆμΆ
.map(String::toUpperCase) // λͺ¨λ λλ¬Έμλ‘ λ³ν
.distinct() // μ€λ³΅ μ κ±°
.forEach(System.out::println); // JAVABAKTXT
μμ 14-6
package chapter14; import java.io.*; import java.util.stream.*; class Main { public static void main(String[] args) { File[] fileArr = {new File("Ex1.java"), new File("Ex1.bak") , new File("Ex2.java"), new File("Ex1"), new File("Ex1.txt") }; // file κ°μ²΄λ€μ΄ λ€μ΄κ°μλ λ°°μ΄ Stream<File> fileStream = Stream.of(fileArr); // μμ file κ°μ²΄λ₯Ό streamμΌλ‘ λ§λ€μλ€. Stream<String> fileNameStream = fileStream.map(File::getName); fileNameStream.forEach(System.out::println); System.out.println("###########"); fileStream = Stream.of(fileArr); // fileStreamμ λ€μ μμ± fileStream.map(File::getName) // Stream<FIle> -> Stream<String> .filter(s -> s.indexOf(".") != -1) // νμ₯μκ° μλ κ²μ μ μΈ .map(s -> s.substring(s.indexOf(".") + 1)) // νμ₯μλ§ μΆμΆ .map(String::toUpperCase) // λͺ¨λ λλ¬Έμλ‘ λ³ν .distinct() // μ€λ³΅ μ κ±° .forEach(System.out::println); // JAVABAKTXT } }
μ€νΈλ¦Όμ μμλ₯Ό μλΉνμ§ μκ³ μΏλ³΄κΈ° - peek()
Stream<T> peek(Consumer<? super T> action) // μ€κ° μ°μ°(μ€νΈλ¦Όμ μλΉX)
void forEach(Consumer<? super T> action) // μ€κ° μ°μ°(μ€νΈλ¦Όμ μλΉO)
fileStream = Stream.of(fileArr); // fileStreamμ λ€μ μμ±
fileStream.map(File::getName) // Stream<FIle> -> Stream<String>
.filter(s -> s.indexOf(".") != -1) // νμ₯μκ° μλ κ²μ μ μΈ
.peek(s -> System.out.printf("fileName = %s%n", s))
.map(s -> s.substring(s.indexOf(".") + 1)) // νμ₯μλ§ μΆμΆ
.peek(s -> System.out.printf("extension = %s%n", s))
.forEach(System.out::println); // μ΅μ’
μ°μ° μ€νΈλ¦Όμ μλΉ
μ€νΈλ¦Όμ μ€νΈλ¦Όμ μ€νΈλ¦ΌμΌλ‘ λ³ν - flatMap()

Stream<String[]> strArrStream = Stream.of()
μμ 14-7
package chapter14; import java.util.*; import java.util.stream.*; class Ex14_7 { public static void main(String[] args) { Stream<String[]> strArrStrm = Stream.of( new String[]{"abc", "def", "jkl"}, new String[]{"ABC", "GHI", "JKL"} ); // Stream<Stream<String>> strStrmStrm = strArrStrm.map(Arrays::stream); // λ°°μ΄μ μ£Όλ©΄ streamμΌλ‘ λ°κΎΌλ€. μ€νΈλ¦Όμ μ€νΈλ¦Όμ΄ μμ±λ¨ Stream<String> strStrm = strArrStrm.flatMap(Arrays::stream); strStrm.map(String::toLowerCase) .distinct() .sorted() .forEach(System.out::println); System.out.println(); String[] lineArr = { "Believe or not It is true", "Do or do not There is no try", }; Stream<String> lineStream = Arrays.stream(lineArr); lineStream.flatMap(line -> Stream.of(line.split(" +"))) .map(String::toLowerCase) .distinct() .sorted() .forEach(System.out::println); System.out.println(); } }
14-35 Optional<T>
- T νμ
κ°μ²΄μ λνΌν΄λμ€ - Optional<T>
public final class Optional<T> { private final T value; // Tνμ μ μ°Έμ‘°λ³μ ... }
14-36 Optional<T> κ°μ²΄ μμ±νκΈ°
- Optional<T> κ°μ²΄λ₯Ό μμ±νλ λ€μν λ°©λ²
String str = "abc"; Optional<String> optVal = Optional.of(str); Optional<String> optVal2 = Optional.of("abc"); Optional<String> optVal3 = Optional.of(null); // NullPointerException λ°μ Optional<String> optVal4 = Optional.ofNullable(null); // OK
public final class Optional<T> { ... private final T value; ... }
- nullλμ λΉ Optional<T> κ°μ²΄λ₯Ό μ¬μ©νμ
Optional<String> optVal = null; // λλ‘ μ΄κΈ°ν. λ°λμ§νμ§ μμ Optional<String> optVal2 = Optional.empty(); // λΉ κ°μ²΄λ‘ μ΄κΈ°ν
14-37 Optional<T> κ°μ²΄μ
- Optional κ°μ²΄μ κ° κ°μ Έμ€κΈ° - get(), orEls(), orElseGet(), orElseThrow()
Optional<String> optVal = Optional.of("abc"); String str1 = optVal.get(); // optValμ μ μ₯λ κ°μ λ°ν. nullμ΄λ©΄ μμΈλ°μ String str2 = optVal.orElse(""); // optValμ μ μ₯λ κ°μ΄ nullμΌ λλ, ""λ₯Ό λ°ν String str3 = optVal.orElseGet(String::new); // λλ€μ μ¬μ©κ°λ₯ () -> new String() String str4 = optVal.orElseThrow(NullPointerException::new); // λμ΄λ©΄ μμΈλ°μ
- isPresent() - Optional κ°μ²΄μ κ°μ΄ nullμ΄λ©΄ false, μλλ©΄ trueλ₯Ό λ°ν
if (Optional.ofNullable(str).isPresent()) { System.out.println(str); } // ifPresent(Consumer) - λμ΄ μλ λλ§ μμ μν, λμ΄λ©΄ μ무 μΌλ μν¨ Optional.ofNullable(str).ifPresent(System.out::println);
μμ
// int[] arr = null; // NEP λ°μ
int[] arr = new int[0];
System.out.println("arr.length = " + arr.length);
// Optional<String> opt = null; // OK. νμ§λ§ λ°λμ§X
Optional<String> opt = Optional.empty();
// Optional<String> opt = Optional.of("abc");
System.out.println("opt" + opt);
// System.out.println("opt" + opt.get());
String str = "";
// try {
// str = opt.get();
// } catch (Exception e) {
// str = ""; // μμΈκ° λ°μνλ©΄ λΉλ¬Έμμ΄("")λ‘ μ΄κΈ°ν
// }
str = opt.orElse("EMPTY"); // Optinalμ μ μ₯λ κ°μ΄ nullμ΄λ©΄ "EMPTY" λ°ν
str = opt.orElseGet(() -> new String()); // Optinalμ μ μ₯λ κ°μ΄ nullμ΄λ©΄ "" λ°ν
str = opt.orElseGet(String::new); // Optinalμ μ μ₯λ κ°μ΄ nullμ΄λ©΄ "" λ°ν
System.out.println("str = " + str);
14-38 OptionallInt, OptionalLong, OptionalDouble
- κΈ°λ³Έν κ°μ κ°μΈλ λνΌν΄λμ€(μ±λ₯ λλ¬Έμ μ¬μ©νλ€.)
public final class OptionalInt { ... private final boolean isPresent; // κ°μ΄ μ μ₯λμ΄ μμΌλ©΄ true private final int value; // int νμ μ λ³μ }
- OptionallIntμ κ° κ°μ Έμ€κΈ° - int getAsInt()
Optinal ν΄λμ€ κ°μ λ°ννλ λ©μλ Optional<T> T get() OptionalInt int getAsInt() OptionalLong long getAsLong() OptionalDouble double getAsDouble()
- λΉ Optional κ°μ²΄μμ λΉκ΅
OptionalInt opt = OptionalInt.of(0); // OptionalIntμ 0μ μ μ₯ OptionalInt opt2 = OptionalInt.empty(); // OptionalIntμ 0μ μ μ₯ System.out.println(opt.isPresent()); // true System.out.println(opt2.isPresent()); // false System.out.println(opt.equals(opt2)); // false
14-40 μ€νΈλ¦Όμ μ΅μ’ μ°μ° - forEach()
- μ€νΈλ¦Όμ λͺ¨λ μμμ μ§μ λ μμ
μ μν - forEach(), forEachOrdered()
μλ λ λ©μλλ κ·Όλ³Έμ μΌλ‘ κ°μλ° λ³λ ¬μΌ λ μ°¨μ΄κ°λλ€.
void forEach(Consumer<? super T> action) // λ³λ ¬μ€νΈλ¦ΌμΈ κ²½μ° μμκ° λ³΄μ₯λμ§ μμ void forEachOrdered(Consumer<? super T> action) // λ³λ ¬μ€νΈλ¦ΌμΈ κ²½μ°μλ μμκ° λ³΄μ₯λ¨
// μ§λ ¬ μ€νΈλ¦Ό, μ€νΈλ¦Όμ κΈ°λ³Έμ μΌλ‘ μ§λ ¬μ΄κΈ° λλ¬Έμ μλ΅ κ°λ₯ IntStream.range(1, 10).sequential().forEach(System.out::println); IntStream.range(1, 10).sequential().forEachOrdered(System.out::println);
// λ³λ ¬ μ€νΈλ¦Ό IntStream.range(1, 10).parallel().forEach(System.out::println); IntStream.range(1, 10).parallel().forEachOrdered(System.out::println);
λ³λ ¬ β μ¬λ¬ μ°λ λκ° λλ μ μμ νλ€.
14-41 μ€νΈλ¦Όμ μ΅μ’ μ°μ° - 쑰건 κ²μ¬
- allMath(), anyMatch(), noneMatch()
boolean allMatch (Predicate<? super T> predicate) // λͺ¨λ μμκ° μ‘°κ±΄μ λ§μ‘±μν€λ©΄ true boolean anyMatch (Predicate<? super T> predicate) // ν μμλΌλ 쑰건μ λ§μ‘±μν€λ©΄ true boolean noneMatch (Predicate<? super T> predicate) // λͺ¨λ μμκ° μ‘°κ±΄μ λ§μ‘±μν€μ§ μμΌλ©΄ true
boolean hasFailedStu = studentStream.anyMatch(s -> s.getTotalScore() <= 100); // λμ μκ° μλμ§?
- 쑰건μ μΌμΉνλ μμ μ°ΎκΈ° - findFirst(), findAny()
쑰건μ λ§λ κ² μμ μλ μκΈ° λλ¬Έμ Optionalλ‘ λμ΄μλ€.
Optional<T> findFirst() // 첫 λ²μ§Έ μμλ₯Ό λ°ν. μμ°¨ μ€νΈλ¦Όμ μ¬μ© Optional<T> findAny() // μ무거λ νλλ₯Ό λ°ν. λ³λ ¬ μ€νΈλ¦Όμ μ¬μ©
Optional<Student> result = studentStream.filter(s -> s.getTotalScore() <= 100).findFirst(); Optional<Student> result = studentStream.parallel().filter(s -> s.getTotalScore() >= 100).findAny();
14-42, 43 μ€νΈλ¦Όμ μ΅μ’ μ°μ° - reduce()
μ€νΈλ¦Όμ μ΅μ’ μ°μ° μ€μ μ μΌ μ€μνλ€. / accumulate - λμ νλ€
ν΅μ¬ : reduce(identity, accumulator)
14-45 collector()μ Collectors
μ΅μ’ μ°μ°
- reduce() : 리λμ±
- collect() : κ·Έλ£Ήλ³ λ¦¬λμ±
collect() : μ΅μ’ μ°μ°
collector : μΈν°νμ΄μ€
collectors : ν΄λμ€
- collect()λ Collectorλ₯Ό λ§€κ°λ³μλ‘ νλ μ€νΈλ¦Όμ μ΅μ’ μ°μ°
14-46 μ€νΈλ¦Όμ 컬λ μ , λ°°μ΄λ‘ λ³ν
- μ€νΈλ¦Όμ 컬λ μ
μΌλ‘ λ³ν - toList(), toSet(), toMap(), toCollection()
List<String> names = stuStream.map(Student::getName) // Stream<Student> -> Stream<String> .collect(Collectors.toList()); // Stream<String> -> List<String> ArrayList<String> list = names.stream() .collect(Collectors.toList()); // Stream<String> -> ArrayList<String> Map<String, Person> map = personStream .collect(Collectors.toMap(p -> p.getRegId(), p -> p)); // Stream<Person> -> Map<String, Person>
- μ€νΈλ¦Όμ λ°°μ΄λ‘ λ³ν - toArray()
Student[] stuNames = studentStream.toArray(Student[]::new); // OK Student[] stuNames = studentStream.toArray(); // μλ¬ Object[] stuNames = studentStream.toArray(); // OK.
14-47 μ€νΈλ¦Όμ ν΅κ³ - counting(), summingInt()
- μ€νΈλ¦Όμ ν΅κ³μ 보 μ 곡 - counting(), summingInt(), maxBy(), minBy(), β¦
long count = stuStream.count(); long count = stuStream.collect(counting()); // Collectors.counting()
long totalScore = stuStream.mapToInt(Student::getTotalScore).sum(); // IntStreamμ sum(), μ μ²΄λ§ κ°λ₯ long totalScore = stuStream.collect(summingInt(Student::getTotalScore)); // κ·Έλ£Ήλ³ κ°λ₯
14-48 μ€νΈλ¦Όμ 리λμ± - reducing()
14-53 μ€νΈλ¦Όμ κ·Έλ£Ήν - groupingBy()
- μ€νΈλ¦Όμ μμλ₯Ό κ·Έλ£Ήν
Collector groupingBy(Function classifier) Collector groupingBy(Function classifier, Collector downstream) Collector groupingBy(Function classifier, Supplier mapFactory, Collector downstream)
Map<Integer, List<Student>> stuByBan = stuStream // νμμ λ°λ³λ‘ κ·Έλ£Ήν .collect(groupingBy(Student::getBan, toList())); // toList() μλ΅κ°λ₯
Map<Integer, Map<Integer, List<Student>> stuByHak // λ€μ€ κ·Έλ£Ήν stuStream.collect(groupingBy(Student::getHak, // 1. νλ λ³ κ·Έλ£Ήν groupingBy(Student::getBan) // 2. λ°λ³ κ·Έλ£Ήν ));



Uploaded by N2T