stream
Search
โข
๊ฒ์ํ ๊ด๋ จ ๊ธฐ๋ฅ์ ๋ด์ ์ธํฐํ์ด์ค ๊ตฌํ ๋ก์ง
package com.practice;
import java.util.List;
import java.util.Map;
public interface PostSystem {
// ํน์ ์์ฑ์(author)๊ฐ ์์ฑํ ๊ฒ์๋ฌผ๋ค์ ํํฐ๋งํ์ฌ ๋ฐํํ๋ ๋ฉ์๋
List<Post> filterPostsByAuthor(List<Post> posts, String author);
// ๋ชจ๋ ๊ฒ์๋ฌผ์ ๋๊ธ์ ์ถ์ถํ์ฌ ๋ฆฌ์คํธ๋ก ๋ฐํํ๋ ๋ฉ์๋
List<Comment> getAllComments(List<Post> posts);
// ๋ชจ๋ ๊ฒ์๋ฌผ์ ์ ๋ชฉ์ ์ถ์ถํ์ฌ ๋ฆฌ์คํธ๋ก ๋ฐํํ๋ ๋ฉ์๋
List<String> getAllPostTitles(List<Post> posts);
// ํน์ ํค์๋(keyword)๋ฅผ ํฌํจํ๋ ๊ฒ์๋ฌผ๋ค์ ํํฐ๋งํ์ฌ ๋ฐํํ๋ ๋ฉ์๋
List<Post> filterPostsByKeyword(List<Post> posts, String keyword);
// ๊ฐ ๊ฒ์๋ฌผ์ ๋๊ธ ์๋ฅผ ๊ณ์ฐํ์ฌ ๋งต ํํ๋ก ๋ฐํํ๋ ๋ฉ์๋
// ๊ฒ์๋ฌผ ID๋ฅผ ํค๋ก ํ๊ณ ๋๊ธ ์๋ฅผ ๊ฐ์ผ๋ก ํ๋ ๋งต
Map<Integer, Integer> getCommentCountByPost(List<Post> posts);
// ์ต์ ๊ฒ์๋ฌผ 3๊ฐ๋ฅผ ์ถ์ถํ์ฌ ๋ฆฌ์คํธ๋ก ๋ฐํํ๋ ๋ฉ์๋
List<Post> getLatestPosts(List<Post> posts);
// ๊ฒ์๋ฌผ ๋ฒํธ ์ค ๊ฐ์ฅ ๋์ ๊ฒ์๋ฌผ ๋ฒํธ๋ฅผ ๋ฐํํ๋ ๋ฉ์๋
int getHighestPostId(List<Post> posts);
// ๊ฒ์๋ฌผ ์
๋ ฅ ๋ฐ๊ธฐ ๋ฉ์๋
void insertPost(List<Post> pList);
}
โข
์ธํฐํ์ด์ค์์ ๊ตฌํํ ๋ฉ์๋์ ๊ตฌ์ฒด์ ์ธ ๋์ ๊ตฌํ์ ์ ๋ฆฌํ ์ฝ๋
package com.practice;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
public class PostSystemImpl implements PostSystem {
// ํน์ ์์ฑ์(author)๊ฐ ์์ฑํ ๊ฒ์๋ฌผ๋ค์ ํํฐ๋งํ์ฌ ๋ฐํํ๋ ๋ฉ์๋
@Override
public List<Post> filterPostsByAuthor(List<Post> posts, String author) {
return posts
.stream()
.filter(post -> post.getAuthor().equals(author))
.collect(Collectors.toList());
}
// ๋ชจ๋ ๊ฒ์๋ฌผ์ ๋๊ธ์ ์ถ์ถํ์ฌ ๋ฆฌ์คํธ๋ก ๋ฐํํ๋ ๋ฉ์๋ - flatMap ํ์ฉํ์ฌ stream ๋ณํ
@Override
public List<Comment> getAllComments(List<Post> posts) {
return posts
.stream()
.flatMap(post -> post.getComments().stream()) // stream์ผ๋ก ๋ณํ
.collect(Collectors.toList());
}
// ๋ชจ๋ ๊ฒ์๋ฌผ์ ์ ๋ชฉ์ ์ถ์ถํ์ฌ ๋ฆฌ์คํธ๋ก ๋ฐํํ๋ ๋ฉ์๋
@Override
public List<String> getAllPostTitles(List<Post> posts) {
return posts.stream()
.map(Post::getTitle)
.collect(Collectors.toList());
}
// ํน์ ํค์๋(keyword)๋ฅผ ํฌํจํ๋ ๊ฒ์๋ฌผ๋ค์ ํํฐ๋งํ์ฌ ๋ฐํํ๋ ๋ฉ์๋ - ์ ๋ชฉ or ๋ด์ฉ ํฌํจ
@Override
public List<Post> filterPostsByKeyword(List<Post> posts, String keyword) {
return posts.stream()
.filter(post -> post.getContent().contains(keyword) || post.getTitle().contains(keyword))
.collect(Collectors.toList());
}
// ๊ฐ ๊ฒ์๋ฌผ์ ๋๊ธ ์๋ฅผ ๊ณ์ฐํ์ฌ ๋งต ํํ๋ก ๋ฐํํ๋ ๋ฉ์๋
// ๊ฒ์๋ฌผ ID๋ฅผ ํค๋ก ํ๊ณ ๋๊ธ ์๋ฅผ ๊ฐ์ผ๋ก ํ๋ ๋งต
@Override
public Map<Integer, Integer> getCommentCountByPost(List<Post> posts) {
return posts
.stream()
.collect(Collectors.toMap(
post -> post.getId(),
post -> post.getComments().size()
));
}
// ์ต์ ๊ฒ์๋ฌผ 3๊ฐ๋ฅผ ์ถ์ถํ์ฌ ๋ฆฌ์คํธ๋ก ๋ฐํํ๋ ๋ฉ์๋
@Override
public List<Post> getLatestPosts(List<Post> posts) {
return posts
.stream()
// .sorted((p1, p2) -> p2.getCreatedAt().compareTo(p1.getCreatedAt()))
.sorted(Comparator.comparing(Post::getCreatedAt).reversed())
.limit(3) // ํ์ด์ง ๊ฒ์ ์กฐํ ์ ์ ํ
.collect(Collectors.toList());
}
// ๊ฒ์๋ฌผ ๋ฒํธ ์ค ๊ฐ์ฅ ๋์ ๊ฒ์๋ฌผ ๋ฒํธ๋ฅผ ๋ฐํํ๋ ๋ฉ์๋
@Override
public int getHighestPostId(List<Post> posts) {
Optional<Post> optMaxPost = posts
.stream()
.max(Comparator.comparing(Post::getId));
Post p = optMaxPost.orElse(null);
return p == null ? 0 : p.getId();
}
// ๊ฒ์๋ฌผ ์
๋ ฅ ๋ฐ๊ธฐ ๋ฉ์๋
@Override
public void insertPost(List<Post> pList) {
System.out.println("๊ฒ์๋ฌผ ์์ฑ");
Scanner sc = new Scanner(System.in);
System.out.println("์ ๋ชฉ ์
๋ ฅ : ");
String title = sc.nextLine();
System.out.println("๋ด์ฉ ์
๋ ฅ : ");
String content = sc.nextLine();
System.out.println("์ด๋ฆ ์
๋ ฅ : ");
String author = sc.nextLine();
pList.add(new Post(getHighestPostId(pList) + 1, title, content,
author, LocalDateTime.now(), new ArrayList<Comment>()));
sc.close();
}
}

๊ฒ์ํ ๊ด๋ จ ๋ฉ์๋ ์ ๋ฆฌ
ํํฐ๋ง(filtering)
Stream์ ์ปฌ๋ ์
์ ์์๋ฅผ ํํฐ๋งํ๋ ๊ธฐ๋ฅ์ ์ ๊ณตํ๋ค.
filter() ๋ฉ์๋๋ฅผ ์ฌ์ฉํ์ฌ ์กฐ๊ฑด์ ๋ง๋ ์์๋ง ์ ํํ ์ ์๋ค.
// ์์
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> evenNumbers = numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
// evenNumbers: [2, 4]
๋งคํ(mapping)
Stream์ ์ปฌ๋ ์
์ ์์๋ฅผ ๋ค๋ฅธ ๊ฐ์ผ๋ก ๋ณํํ๋ ๋งคํ ๊ธฐ๋ฅ์ ์ ๊ณตํ๋ค.
map() ๋ฉ์๋๋ฅผ ์ฌ์ฉํ์ฌ ๊ฐ ์์๋ฅผ ์ํ๋ ๊ฐ์ผ๋ก ๋ณํํ ์ ์๋ค.
// ์์
List<String> names = Arrays.asList("John", "Paul", "George", "Ringo");
List<Integer> nameLengths = names.stream()
.map(String::length)
.collect(Collectors.toList());
// nameLengths: [4, 4, 6, 5]

java stream ์ฌ์ฉ๋ฒ ์ ๋ฆฌ
โข
Order
package com.stream;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.List;
@Data
@AllArgsConstructor
public class Order {
private List<Product> products;
}
โข
Product
package com.stream;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Product {
private String name;
}
โข
User
package com.stream;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Product {
private String name;
}
โข
PracticeExample

stream ์์ ์ฝ๋ 1
โข
๋ณ๋ ฌ ์คํธ๋ฆผ(parallelStream) ๊ด๋ จ ์ฝ๋ ์์
package com.stream1;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class StreamExample {
public static void main(String[] args) {
List<String> languageList = new ArrayList<>();
languageList.add("Java");
languageList.add("JavaScript");
languageList.add("Python");
languageList.add("C");
// ๋ณ๋ ฌ ์คํธ๋ฆผ ์ป๊ธฐ
Stream<String> parallelStream = languageList.parallelStream();
parallelStream.forEach(name -> {
System.out.println(name + " : " + Thread.currentThread().getName());
});
System.out.println("===============================================");
// for ๋ฌธ์ผ๋ก ๋์์ํค๊ธฐ
for (String name : languageList) {
System.out.println(name + " : " + Thread.currentThread().getName());
}
}
}

stream ์์ ์ฝ๋ 2 - ๋ณ๋ ฌ ์คํธ๋ฆผ
โข
Student.java
package com.stream2;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Student {
private String name;
private int score;
}
โข
StreamExample.java
package com.stream2;
import java.util.Arrays;
import java.util.List;
import java.util.OptionalDouble;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class StreamExample {
public static void main(String[] args) {
List<Student> sList = Arrays.asList(
new Student("Alice", 90),
new Student("Bob", 80),
new Student("Jonathan", 85),
new Student("David", 95)
);
// Stream<Student> originalStream = sList.stream();
// IntStream intStream = originalStream.mapToInt(Student::getScore);
// OptionalDouble optAverage = intStream.average();
// double avg = optAverage.getAsDouble();
double avg = sList.stream()
.mapToInt(Student::getScore). // s -> s.getScore()
.average()
.getAsDouble();
System.out.println(avg);
}
}

stream ์์ ์ฝ๋ 3 - mapToInt, average()
โข
Product.java
package com.stream3;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Product {
private int pno, price;
private String name, company;
}
โข
ProductExample.java
package com.stream3;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class ProductExample {
public static void main(String[] args) {
List<Product> pList = new ArrayList<>();
for (int i = 1; i <= 5; i++) {
Product p = new Product(i, (int) (10000 * Math.random()), "์ํ" + i, "ํ์ฌ๋ช
");
pList.add(p);
}
// Stream<Product> stream = pList.stream();
double proWithAvg = pList.stream()
.mapToInt(Product::getPrice)
.average()
.getAsDouble();
pList.stream().forEach(System.out::println);
System.out.println(proWithAvg);
}
}

stream ์์ ์ฝ๋ 4
โข
๋ฐฐ์ด๋ก๋ถํฐ ์คํธ๋ฆผ ์ป๋ ๋ฐฉ๋ฒ ์ ๋ฆฌ
package com.stream4;
import java.util.Arrays;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class StreamExample {
public static void main(String[] args) {
String[] strArr = {"๋งฅ๋ถ", "์ด์ดํฐ", "์์ดํ"};
// ๋ฐฐ์ด๋ก๋ถํฐ ์คํธ๋ฆผ ์ป๋ ๋ ๊ฐ์ง ๋ฐฉ๋ฒ
Stream<String> strStream1 = Stream.of(strArr);
Stream<String> strStream2 = Arrays.stream(strArr);
strStream1.forEach(i -> System.out.print(i + ", "));
System.out.println();
strStream2.forEach(i -> System.out.print(i + ", "));
System.out.println("\n");
int[] intArr = { 3, 1, 4, 1, 5, 9, 2 };
// ๋ฐฐ์ด๋ก๋ถํฐ ์คํธ๋ฆผ ์ป๋ ๋ ๊ฐ์ง ๋ฐฉ๋ฒ
IntStream intStream1 = IntStream.of(intArr);
IntStream intStream2 = Arrays.stream(intArr);
intStream1.forEach(i -> System.out.print(i + ", "));
System.out.println();
intStream2.forEach(i -> System.out.print(i + ", "));
}
}

stream ์์ ์ฝ๋ 5 - ๋ฐฐ์ด๋ก๋ถํฐ ์คํธ๋ฆผ ์ป๋ ๋ฐฉ๋ฒ
โข
Product.java
package com.stream6;
import lombok.AllArgsConstructor;
import lombok.Data;
@AllArgsConstructor
@Data
public class Product {
private int pno;
private String pname;
private String pCompany;
private int price;
}
โข
StreamExample.java
package com.stream6;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class StreamExample {
public static void main(String[] args) throws IOException {
String absolutePath = "/Users/haminsung/Desktop/test/java/data.txt";
Path path = Paths.get(absolutePath);
Stream<String> stream = Files.lines(path, Charset.defaultCharset());
// stream.forEach(line -> System.out.println(line));
stream.forEach(l -> {
String[] productInfo = l.split(" ");
int pno = Integer.parseInt(productInfo[0]);
String pName = productInfo[1];
String pCompany = productInfo[2];
int price = Integer.parseInt(productInfo[3]);
Product p = new Product(pno, pName, pCompany, price);
System.out.println(p);
});
stream.close();
}
}

stream ์์ ์ฝ๋ 6 - Stream ํ์ฉํ์ฌ ํ์ผ ์ฝ์ด์ค๊ธฐ
โข
Student.java
package com.stream8;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Student {
private String name;
private int score;
}
โข
MappingExample.java
package com.stream8;
import java.util.Arrays;
import java.util.List;
public class MappingExample {
public static void main(String[] args) {
List<Student> sList = Arrays.asList(
new Student("James", 90),
new Student("Paul", 80),
new Student("John", 85),
new Student("Kane", 95)
);
sList
.stream()
// .map(s -> s.getName())
// .forEach(name -> System.out.println(name));
.map(Student::getName)
.forEach(System.out::println);
}
}

stream ์์ ์ฝ๋ 7 - map ํ์ฉ
package com.stream9;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class MappingExample {
public static void main(String[] args) {
// ์คํธ๋ฆผ์ผ๋ก ์์๋ง ํฌํจํ๋ ์๋ก์ด ๋ฆฌ์คํธ๋ก ๋ฐํ
// ํํฐ๋ง๋ ์๋ก์ด ๋ฆฌ์คํธ ์ถ๋ ฅ
List<Integer> primeList = IntStream.rangeClosed(1, 1000)
.filter(x -> isPrime(x)) // ํํฐ๋ง
.boxed()
.collect(Collectors.toList()); // ๋ฆฌ์คํธ๋ก ๋ฐํ
System.out.println(primeList);
System.out.println();
// 1๋ถํฐ 5๊น์ง์ IntStream ์์ฑ.. Double stream ํ์
์ผ๋ก ๋ณํํ๊ณ ์ถ๋ ฅํ๊ธฐ
IntStream
.range(1, 6)
.asDoubleStream()
.forEach(v -> System.out.println(v));
// 1๋ถํฐ 5๊น์ง์ IntStream ์์ฑ.. double ํ์
์ผ๋ก ๋ณํํ๊ณ ์ถ๋ ฅํ๊ธฐ
List<Double> doubleList = IntStream
.range(1, 6)
.asDoubleStream()
.boxed()
.collect(Collectors.toList());
System.out.println(doubleList);
}
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
package com.stream7;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamFilterExample {
public static void main(String[] args) {
List<String> nameList = Arrays.asList("์ฐ์ํ", "ํฉ์ ์ฐ", "๊น์ฐ๋ฏผ", "์์ฑํ", "์ ์ ๋น", "์ฐ์ํ");
// distinct๋ก ์ค๋ณต์ด ์ ๊ฑฐ๋์๋ค!
nameList.stream()
.distinct()
.forEach(n -> System.out.print(n + ", "));
System.out.println();
// filter๋ก "์ฐ"๊ฐ ๋ค์ด๊ฐ ์ด๋ฆ๋ง ๋์จ๋ค.
nameList.stream()
.filter(n -> n.contains("์ฐ"))
.forEach(n -> System.out.print(n + ", "));
System.out.println();
System.out.println("=======================================");
// distinct๋ก ์ค๋ณต๋ ์์๊ฐ ์ ๊ฑฐํ๊ณ , filter๋ก "์ฐ"๊ฐ ๋ค์ด๊ฐ ์ด๋ฆ๋ง ๋์ค๊ฒ ํ๊ธฐ
// nameList.stream()
// .distinct()
// .filter(n -> n.contains("์ฐ"))
// .forEach(n -> System.out.print(n + ", "));
// ๋ฆฌ์คํธ ํํ๋ก ์ถ๋ ฅ๋จ
List<String> filteredList = nameList
.stream()
.distinct()
.filter(n -> n.contains("์ฐ"))
.collect(Collectors.toList()); // ๋ฆฌ์คํธ ํํ๋ก ๋ณํ
System.out.println(filteredList);
}
}
package com.stream7;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.Stream;
public class StreamFilterExample2 {
public static void main(String[] args) {
// 1๋ถํฐ 1000๊น์ง ์ซ์ ์์ฑ
IntStream intStream = IntStream.rangeClosed(1, 1000);
intStream.forEach(System.out::println);
// ์คํธ๋ฆผ์ผ๋ก ์์๋ง ํฌํจํ๋ ์๋ก์ด ๋ฆฌ์คํธ๋ก ๋ฐํ
// ํํฐ๋ง๋ ์๋ก์ด ๋ฆฌ์คํธ ์ถ๋ ฅ
IntStream
.rangeClosed(1, 1000)
.filter(x -> isPrime(x))
.forEach(i -> System.out.print(i + ", "));
}
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
return true;
}
return false;
}
}

stream ์์ ์ฝ๋ 8 - ํํฐ๋ง, IntStream
โข
FlatMap
package com.stream10;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
public class FlatMappingExample {
public static void main(String[] args) {
List<String> msgList = new ArrayList<>();
msgList.add("์๋
? ๋ xxx์ผ");
msgList.add("์ฐ๋ฆฌ ๊ฐ์ด xx ํ๊ณ ๋์");
msgList.add("Hello World!");
msgList.stream()
.flatMap(msg -> Arrays.stream(msg.split(" "))) // flatMap
.forEach(word -> System.out.println(word)); // foreach๋ก ๋ฐํ
System.out.println();
List<String> strNums = Arrays.asList("10, 20, 30", "40, 50", "60");
strNums.stream()
.flatMapToInt(e -> {
String[] strArr = e.split(",");
int[] intArr = new int[strArr.length];
for (int i = 0; i < strArr.length; i++) {
intArr[i] = Integer.parseInt(strArr[i].trim());
}
return Arrays.stream(intArr);
// return IntStream.of(intArr);
})
.forEach(i -> System.out.println(i)); // IntStream
}
}

stream ์์ ์ฝ๋ 9 - flatMap
โข
Student.java
package com.stream11;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Student implements Comparable<Student> {
private String name;
private int score;
@Override
public int compareTo(Student o) {
return Integer.compare(score, o.score);
// return score - o.score;
}
}
โข
Student.java
package com.stream11;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Student implements Comparable<Student> {
private String name;
private int score;
@Override
public int compareTo(Student o) {
return Integer.compare(score, o.score);
// return score - o.score;
}
}
โข
SortExample.java

stream ์์ ์ฝ๋ 10 - sort(์ ๋ ฌ)
โข
Employee
package com.assignment;
import lombok.Data;
@Data
public class Employee {
private int id;
private String name;
private String department;
private double salary;
private String email;
// ์์ฑ์, getter, setter ๋ฉ์๋๋ค์ ์์ฑํ์ธ์
public Employee(int id, String name, String department, double salary, String email) {
this.id = id;
this.name = name;
this.department = department;
this.salary = salary;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
โข
EMSystem.java
package com.assignment;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
public class EMSystem {
// ๋ถ์๋ณ ์ง์ ํํฐ๋ง - ํน์ ๋ถ์(department)์ ์ํ ์ง์๋ค์ ํํฐ๋งํ์ฌ ๋ฐํํ๋ ๋ฉ์๋๋ฅผ ์์ฑํ์ธ์.
public List<Employee> filterByDepartment(List<Employee> employees, String department) {
// return employees.stream()
// .filter(employee -> department.contains(employee.getDepartment()))
// .collect(Collectors.toList());
return employees.stream()
.filter(employee -> employee.getDepartment().equals(department))
.toList();
}
// ์ง์ ์ด๋ฉ์ผ ๋ชฉ๋ก ์ถ์ถ - ๋ชจ๋ ์ง์์ ์ด๋ฉ์ผ ์ฃผ์๋ฅผ ์ถ์ถํ์ฌ ๋ฆฌ์คํธ๋ก ๋ฐํํ๋ ๋ฉ์๋๋ฅผ ์์ฑํ์ธ์.
public List<String> getEmailAddresses(List<Employee> employees) {
return employees.stream()
.map(employee -> employee.getEmail())
.collect(Collectors.toList());
}
// ์ง์ ๊ธ์ฌ ํฉ๊ณ ๊ณ์ฐ - ๋ชจ๋ ์ง์์ ๊ธ์ฌ ํฉ๊ณ๋ฅผ ๊ณ์ฐํ์ฌ ๋ฐํํ๋ ๋ฉ์๋๋ฅผ ์์ฑํ์ธ์.
public double getTotalSalary(List<Employee> employees) {
return employees.stream()
.mapToDouble(Employee::getSalary)
.sum();
}
// ํน์ ๊ธ์ฌ ์ด์์ ์ง์ ํํฐ๋ง - ํน์ ๊ธ์ฌ(salary) ์ด์์ ๋ฐ๋ ์ง์๋ค์ ํํฐ๋งํ์ฌ ๋ฐํํ๋ ๋ฉ์๋๋ฅผ ์์ฑํ์ธ์.
public List<Employee> filterBySalary(List<Employee> employees, double salary) {
return employees.stream()
.filter(employee -> employee.getSalary() >= salary)
.collect(Collectors.toList());
}
// // ๋ถ์๋ณ ํ๊ท ๊ธ์ฌ ๊ณ์ฐ - ๊ฐ ๋ถ์๋ณ๋ก ํ๊ท ๊ธ์ฌ๋ฅผ ๊ณ์ฐํ์ฌ ๋งต ํํ๋ก ๋ฐํํ๋ ๋ฉ์๋๋ฅผ ์์ฑํ์ธ์. ๋ถ์ ์ด๋ฆ์ ํค๋ก ํ๊ณ ํ๊ท
// ๊ธ์ฌ๋ฅผ ๊ฐ์ผ๋ก ํ๋ ๋งต์ ๋ฐํํ์ธ์.
public Map<String, Double> getAverageSalaryByDepartment(List<Employee> employees) {
return employees.stream()
.collect(Collectors.groupingBy(
Employee :: getDepartment, // e -> e.getDepartment()
Collectors.averagingDouble(Employee :: getSalary))); // e -> e.getSalary()
}
// // ์ง์ ์ด๋ฆ ์ ๋ ฌ - ์ง์๋ค์ ์ด๋ฆ์ ์ํ๋ฒณ ์์๋ก ์ ๋ ฌํ์ฌ ๋ฐํํ๋ ๋ฉ์๋๋ฅผ ์์ฑํ์ธ์.
public List<Employee> sortEmployeesByName(List<Employee> employees) {
return employees.stream()
.sorted((emp1, emp2) -> emp1.getName().compareTo(emp2.getName()))
.toList();
}
// // ์ง์ ID๋ก ์ง์ ์ฐพ๊ธฐ - ์ง์ ID๋ก ํน์ ์ง์์ ์ฐพ์ ๋ฐํํ๋ ๋ฉ์๋๋ฅผ ์์ฑํ์ธ์. ์ง์์ด ์กด์ฌํ์ง ์์ผ๋ฉด
// Optional.empty()๋ฅผ ๋ฐํํ์ธ์.
public Optional<Employee> findEmployeeById(List<Employee> employees, int id) {
return employees.stream()
.filter(employee -> employee.getId() == id)
.findFirst();
}
}
โข
EmployeeExample.java

stream ์์ ์ฝ๋ 11 - EmployeeSystem
โข
stream์ ํ์ฉํ์ฌ ์กฐ๊ฑด์ ๋ถํฉํ ์ดํฉ ๊ตฌํ๊ธฐ
package com.stream;
import java.util.Arrays;
public class LoopExample {
public static void main(String[] args) {
int[] intArr = {1, 2, 3, 4, 5};
int total = Arrays
.stream(intArr)
.filter(i -> i % 2 == 0)
.peek(System.out::println)
.sum();
System.out.println("์ดํฉ : " + total);
Arrays
.stream(intArr)
.filter(i -> i % 2 == 1)
.forEach(System.out::println);
}
}
โข
stream ํ์ฉํ์ฌ ์ง์, ํ์ ํ๋ณ ๋ฐ ๋ฐฐ์ ํ๋ณ
package com.stream2;
import java.util.Arrays;
import java.util.stream.IntStream;
public class MatchExample {
public static void main(String[] args) {
int[] intArr1 = { 2, 4, 6, 8 };
int[] intArr2 = { 2, 3, 4, 6, 8 };
// ๋ชจ๋ 2์ ๋ฐฐ์์ด๋ฉด true๋ฅผ ๋ฐํ
boolean allEvenResult1 = Arrays.stream(intArr1).allMatch(i -> i % 2 == 0);
boolean allEvenResult2 = IntStream.of(intArr2).allMatch(i -> i % 2 == 0);
System.out.println("1๋ฒ ๋ฐฐ์ด์ด ๋ชจ๋ ์ง์์ธ๊ฐ? " + allEvenResult1);
System.out.println("2๋ฒ ๋ฐฐ์ด์ด ๋ชจ๋ ์ง์์ธ๊ฐ? " + allEvenResult2);
// ํ๋๋ผ๋ ํ์๊ฐ ์์ผ๋ฉด true๋ฅผ ๋ฐํ
boolean anyOddResult1 = Arrays.stream(intArr1).anyMatch(i -> i % 2 == 1);
boolean anyOddResult2 = IntStream.of(intArr2).anyMatch(i -> i % 2 == 1);
System.out.println("1๋ฒ ๋ฐฐ์ด ์ค ํ๋๋ผ๋ ํ์๊ฐ ์๋๊ฐ? " + anyOddResult1);
System.out.println("2๋ฒ ๋ฐฐ์ด ์ค ํ๋๋ผ๋ ํ์๊ฐ ์๋๊ฐ? " + anyOddResult2);
// 10์ ๋ฐฐ์๊ฐ ์์ผ๋ฉด true๋ฅผ ๋ฐํ
boolean notInTenTimes1 = Arrays.stream(intArr1).noneMatch(i -> i % 10 == 1);
boolean notInTenTimes2 = IntStream.of(intArr2).noneMatch(i -> i % 10 == 1);
System.out.println("1๋ฒ ๋ฐฐ์ด ์ค์๋ 10์ ๋ฐฐ์๊ฐ ์๋๊ฐ?" + notInTenTimes1);
System.out.println("2๋ฒ ๋ฐฐ์ด ์ค์๋ 10์ ๋ฐฐ์๊ฐ ์๋๊ฐ?" + notInTenTimes2);
}
}
โข
์์์ ๊ณฑ

stream ์์ ์ฝ๋ 12
โข
์ง๊ณ๊ฐ ์๋ ๊ฒฝ์ฐ ๋๋นํ๋ ๋ฐฉ๋ฒ
package com.stream3;
import java.util.Arrays;
import java.util.OptionalDouble;
public class ReductionExample {
public static void main(String[] args) {
int[] intArr = { 2, 4, 6, 8, 10 };
// ์ง๊ณ๊ฐ์ด ์๋ ๊ฒฝ์ฐ ๋๋นํ๋ ๋ฐฉ๋ฒ 1
OptionalDouble optAvg = Arrays.stream(intArr).average();
if (optAvg.isPresent()) {
System.out.println("ํ๊ท : " + optAvg.getAsDouble());
} else {
// System.out.println("๊ฐ์ด ์์ต๋๋ค.");
System.out.println("ํ๊ท : " + 0.0);
}
// ์ง๊ณ๊ฐ์ด ์๋ ๊ฒฝ์ฐ ๋๋นํ๋ ๋ฐฉ๋ฒ 2
double avg = Arrays.stream(intArr).average().orElse(0.0);
System.out.println("ํ๊ท : " + avg);
System.out.println();
// ์ง๊ณ๊ฐ์ด ์๋ ๊ฒฝ์ฐ ๋๋นํ๋ ๋ฐฉ๋ฒ 3
Arrays.stream(intArr).average().ifPresent(a -> System.out.println(a));
}
}
package com.stream3;
import java.util.ArrayList;
import java.util.List;
import java.util.OptionalDouble;
public class ReductionExample2 {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
OptionalDouble optAvg = list
.stream()
.mapToInt(i -> i.intValue())
.average();
// .isPresent() -> ํ๊ท 1) : 0.0
if (optAvg.isPresent()) {
System.out.println("ํ๊ท 1) : " + optAvg.getAsDouble());
} else {
System.out.println("ํ๊ท 1) : " + 0.0);
}
// .orElse() -> ํ๊ท 2) : 0.0
System.out.println("ํ๊ท 2) : " + optAvg.orElse(0.0));
// .ifPresent -> ํ๊ท 3) :
optAvg.ifPresent(a -> System.out.println("ํ๊ท 3) : " + a));
}
}

stream ์์ ์ฝ๋ 13 - Optional
โข
Beverage.java
package com.stream4;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class Beverage {
private String name;
private int price;
private boolean isIce;
}
โข
CollectExample
package com.stream4;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CollectExample {
public static void main(String[] args) {
List<Beverage> bList = new ArrayList<>();
bList.add(new Beverage("์์ด์ค ์๋ฉ๋ฆฌ์นด๋
ธ", 1500, true));
bList.add(new Beverage("์์ด์ค ์๋ฉ๋ฆฌ์นด๋
ธ", 1500, true));
bList.add(new Beverage("๋ฐ๋ปํ ๋ฐ๋๋ผ ๋ผ๋ผ", 3500, false));
bList.add(new Beverage("์ ๋ก์ฝ๋ผ", 2000, true));
bList.add(new Beverage("์์๋", 2000, true));
bList.add(new Beverage("์ค๋ก ํฐ", 1500, true));
// 2000์์ ์๋ฃ
List<Beverage> two$List = bList.stream().filter(b -> b.getPrice() == 2000).collect(Collectors.toList());
// bList.stream().filter(b -> b.getPrice() == 2000).toList();
System.out.println(two$List);
System.out.println();
// ์๋ฃ์ ์ด๋ฆ ๊ธธ์ด๊ฐ 3์ธ ๊ฒ๋ค
Set<Beverage> threeSet = bList.stream().filter(b -> b.getName().length() == 3).collect(Collectors.toSet());
System.out.println(threeSet);
// ์๋ฃ ์ด๋ฆ, ๊ฐ๊ฒฉ์ผ๋ก ๊ตฌ์ฑ๋ ๊ฒ๋ค
Map<String, Integer> iceMap = bList.stream()
.distinct()
.filter(b -> b.isIce()).collect(Collectors.toMap(b -> b.getName(), b -> b.getPrice()));
System.out.println();
System.out.println(iceMap);
}
}
package com.stream4;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
// ์นดํ
๊ณ ๋ฆฌ ์ํ ์ฝ๋์ ์ฐธ๊ณ
public class CollectExample2 {
public static void main(String[] args) {
List<Beverage> bList = new ArrayList<>();
bList.add(new Beverage("๋ฐ๋ปํ ์๋ฉ๋ฆฌ์นด๋
ธ", 1500, false));
bList.add(new Beverage("๋ฐ๋ปํ ๋ฐ๋๋ผ ๋ผ๋ผ", 3500, false));
bList.add(new Beverage("ํซ์ด์ฝ", 3500, false));
bList.add(new Beverage("์ ๋ก์ฝ๋ผ", 2000, true));
bList.add(new Beverage("์์๋", 2000, true));
bList.add(new Beverage("์ค๋ก ํฐ", 2000, true));
Map<String, Boolean> newBList = bList.stream()
.distinct()
.collect(Collectors.toMap(b -> b.getName(), b -> b.isIce()));
System.out.println(newBList);
System.out.println("============");
// ์ฌ๊ธฐ์ ํ์ฉํ ๋ก์ง์ ์ ์ดํดํด์ผ ํจ
Map<Boolean, List<Beverage>> isIceMap = bList.stream()
.collect(Collectors.groupingBy(b -> (Boolean) b.isIce()));
// ์ฌ๊ธฐ์ ํ์ฉํ ๋ก์ง์ ์ ์ดํดํด์ผ ํจ
for (Map.Entry<Boolean, List<Beverage>> entry : isIceMap.entrySet()) {
System.out.println(entry.getKey() + " : ");
for (Beverage b : entry.getValue()) {
System.out.println("\t" + b);
}
}
List<Beverage> iceList = isIceMap.get(true);
List<Beverage> hotList = isIceMap.get(false);
System.out.println(iceList);
System.out.println(hotList);
System.out.println();
Map<Boolean, Double> isIceAvgPriceMap = bList.stream()
.collect(Collectors.groupingBy(
b -> b.isIce(),
// Collectors.counting()
Collectors.averagingDouble(b -> b.getPrice()
)));
System.out.println(isIceAvgPriceMap);
}
}

stream ์์ ์ฝ๋ 14
โข
https://velog.io/@mooh2jj/Java-๋๋ค์-ํํ๋ค

stream ์์ ์ฐธ๊ณ ์ฌ์ดํธ




