logo

자바 8 스트림

Java는 Java 8에서 java.util.stream이라는 새로운 추가 패키지를 제공합니다. 이 패키지는 요소에 대한 기능적 스타일 작업을 허용하는 클래스, 인터페이스 및 열거형으로 구성됩니다. java.util.stream 패키지를 import하여 스트림을 사용할 수 있습니다.


Stream은 다음과 같은 기능을 제공합니다.

  • 스트림은 요소를 저장하지 않습니다. 이는 단순히 계산 작업 파이프라인을 통해 데이터 구조, 배열 또는 I/O 채널과 같은 소스의 요소를 전달합니다.
  • 스트림은 본질적으로 기능적입니다. 스트림에서 수행되는 작업은 해당 소스를 수정하지 않습니다. 예를 들어 컬렉션에서 얻은 스트림을 필터링하면 소스 컬렉션에서 요소를 제거하는 대신 필터링된 요소 없이 새 스트림이 생성됩니다.
  • 스트림은 게으르고 필요한 경우에만 코드를 평가합니다.
  • 스트림의 요소는 스트림 수명 동안 한 번만 방문됩니다. Iterator와 마찬가지로 소스의 동일한 요소를 다시 방문하려면 새 스트림을 생성해야 합니다.

스트림을 사용하여 한 데이터 구조에서 다른 데이터 구조로 필터링, 수집, 인쇄 및 변환할 수 있습니다. 다음 예에서는 스트림을 사용하여 다양한 작업을 적용했습니다.

Java 스트림 인터페이스 메소드

행동 양식 설명
boolean allMatch(술어 술어) 제공된 조건자와 일치하는 이 스트림의 모든 요소를 ​​반환합니다. 스트림이 비어 있으면 true가 반환되고 조건자는 평가되지 않습니다.
boolean anyMatch(술어 술어) 제공된 조건자와 일치하는 이 스트림의 모든 요소를 ​​반환합니다. 스트림이 비어 있으면 false가 반환되고 조건자는 평가되지 않습니다.
정적 Stream.Builder 빌더() 스트림에 대한 빌더를 반환합니다.
R 수집(수집기 수집기) Collector를 사용하여 이 스트림의 요소에 대해 변경 가능한 축소 작업을 수행합니다. Collector는 수집(Supplier, BiConsumer, BiConsumer)에 대한 인수로 사용되는 함수를 캡슐화하여 수집 전략을 재사용하고 다중 수준 그룹화 또는 분할과 같은 수집 작업을 구성할 수 있도록 합니다.
R 수집(공급자 공급자, BiConsumer 누산기, BiConsumer 결합기) 이 스트림의 요소에 대해 변경 가능한 축소 작업을 수행합니다. 변경 가능한 축소는 축소된 값이 ArrayList와 같은 변경 가능한 결과 컨테이너이고, 결과를 바꾸는 것이 아니라 결과의 상태를 업데이트하여 요소가 통합되는 것입니다.
정적 스트림 연결(스트림 a, 스트림 b) 첫 번째 스트림의 모든 요소와 두 번째 스트림의 모든 요소가 이어지는 지연 연결 스트림을 생성합니다. 두 입력 스트림이 모두 정렬되면 결과 스트림이 정렬되고, 입력 스트림 중 하나가 병렬이면 병렬이 됩니다. 결과 스트림이 닫히면 두 입력 스트림 모두에 대한 닫기 핸들러가 호출됩니다.
긴 카운트() 이 스트림의 요소 수를 반환합니다. 이는 감소의 특별한 경우입니다.
스트림 구별() 이 스트림의 고유한 요소(Object.equals(Object)에 따라)로 구성된 스트림을 반환합니다.
정적 스트림 비어 있음() 빈 순차 스트림을 반환합니다.
스트림 필터(Predicate predicate) 주어진 조건과 일치하는 이 스트림의 요소로 구성된 스트림을 반환합니다.
선택적 findAny() 스트림의 일부 요소를 설명하는 Optional을 반환하거나, 스트림이 비어 있으면 빈 Optional을 반환합니다.
선택적 findFirst() 이 스트림의 첫 번째 요소를 설명하는 Optional을 반환하거나, 스트림이 비어 있으면 빈 Optional을 반환합니다. 스트림에 발생 순서가 없으면 모든 요소가 반환될 수 있습니다.
스트림 flatMap(함수매퍼) 이 스트림의 각 요소를 각 요소에 제공된 매핑 함수를 적용하여 생성된 매핑된 스트림의 콘텐츠로 대체한 결과로 구성된 스트림을 반환합니다. 매핑된 각 스트림은 해당 콘텐츠가 이 스트림에 배치된 후 닫힙니다. (매핑된 스트림이 null이면 대신 빈 스트림이 사용됩니다.)
DoubleStream flatMapToDouble(함수 매퍼) 이 스트림의 각 요소를 각 요소에 제공된 매핑 함수를 적용하여 생성된 매핑된 스트림의 콘텐츠로 대체한 결과로 구성된 DoubleStream을 반환합니다. 매핑된 각 스트림은 해당 콘텐츠가 이 스트림에 배치된 후 닫힙니다. (매핑된 스트림이 null이면 대신 빈 스트림이 사용됩니다.)
IntStream flatMapToInt(함수 매퍼) 이 스트림의 각 요소를 각 요소에 제공된 매핑 함수를 적용하여 생성된 매핑된 스트림의 콘텐츠로 대체한 결과로 구성된 IntStream을 반환합니다. 매핑된 각 스트림은 해당 콘텐츠가 이 스트림에 배치된 후 닫힙니다. (매핑된 스트림이 null이면 대신 빈 스트림이 사용됩니다.)
LongStream flatMapToLong(함수 매퍼) 이 스트림의 각 요소를 각 요소에 제공된 매핑 함수를 적용하여 생성된 매핑된 스트림의 콘텐츠로 대체한 결과로 구성된 LongStream을 반환합니다. 매핑된 각 스트림은 해당 콘텐츠가 이 스트림에 배치된 후 닫힙니다. (매핑된 스트림이 null이면 대신 빈 스트림이 사용됩니다.)
void forEach(소비자 행동) 이 스트림의 각 요소에 대해 작업을 수행합니다.
void forEachOrdered(소비자 행동) 스트림에 정의된 만남 순서가 있는 경우 스트림의 만남 순서에 따라 이 스트림의 각 요소에 대한 작업을 수행합니다.
정적 스트림 생성(공급업체) 제공된 공급자에 의해 각 요소가 생성되는 무한한 순차적 비순차적 스트림을 반환합니다. 이는 상수 스트림, 임의 요소 스트림 등을 생성하는 데 적합합니다.
정적 스트림 반복(T 시드, UnaryOperator f) 초기 요소 시드에 함수 f를 반복적으로 적용하여 생성된 무한 순차 순서 스트림을 반환하고 시드, f(시드), f(f(시드)) 등으로 구성된 스트림을 생성합니다.
스트림 제한(긴 maxSize) 길이가 maxSize보다 길지 않도록 잘린 이 스트림의 요소로 구성된 스트림을 반환합니다.
스트림 맵(함수 매퍼) 주어진 함수를 이 스트림의 요소에 적용한 결과로 구성된 스트림을 반환합니다.
DoubleStream mapToDouble(ToDoubleFunction 매퍼) 이 스트림의 요소에 주어진 함수를 적용한 결과로 구성된 DoubleStream을 반환합니다.
IntStream mapToInt(ToIntFunction 매퍼) 이 스트림의 요소에 주어진 함수를 적용한 결과로 구성된 IntStream을 반환합니다.
LongStream mapToLong(ToLongFunction 매퍼) 이 스트림의 요소에 주어진 함수를 적용한 결과로 구성된 LongStream을 반환합니다.
선택적 max(비교기 비교기) 제공된 비교기에 따라 이 스트림의 최대 요소를 반환합니다. 이는 감소의 특별한 경우입니다.
Optional min(비교기 비교기) 제공된 Comparator에 따라 이 스트림의 최소 요소를 반환합니다. 이는 감소의 특별한 경우입니다.
boolean noneMatch(술어 술어) 제공된 조건자와 일치하는 이 스트림의 요소를 반환합니다. 스트림이 비어 있으면 true가 반환되고 조건자는 평가되지 않습니다.
@SafeVarargs 정적 스트림(T... 값) 요소가 지정된 값인 순차적으로 정렬된 스트림을 반환합니다.
정적 스트림(T t) 단일 요소를 포함하는 순차적 스트림을 반환합니다.
스트림 엿보기(소비자 행동) 이 스트림의 요소로 구성된 스트림을 반환하고 결과 스트림에서 요소가 소비될 때 각 요소에 대해 제공된 작업을 추가로 수행합니다.
선택적 축소(BinaryOperator 누산기) 연관 누적 함수를 사용하여 이 스트림의 요소에 대한 감소를 수행하고 감소된 값(있는 경우)을 설명하는 Optional을 반환합니다.
T 감소(T 항등식, BinaryOperator 누산기) 제공된 ID 값과 연관 누적 함수를 사용하여 이 스트림의 요소에 대한 감소를 수행하고 감소된 값을 반환합니다.
U 감소(U 항등식, BiFunction 누산기, BinaryOperator 결합기) 제공된 항등, 누적 및 결합 기능을 사용하여 이 스트림의 요소에 대한 축소를 수행합니다.
스트림 건너뛰기(long n) 스트림의 처음 n개 요소를 버린 후 이 스트림의 나머지 요소로 구성된 스트림을 반환합니다. 이 스트림에 n개 미만의 요소가 포함되어 있으면 빈 스트림이 반환됩니다.
스트림 정렬() 이 스트림의 요소로 구성된 스트림을 자연 순서에 따라 정렬하여 반환합니다. 이 스트림의 요소가 비교 가능하지 않은 경우 터미널 작업이 실행될 때 java.lang.ClassCastException이 발생할 수 있습니다.
스트림 정렬(비교기 비교기) 제공된 비교기에 따라 정렬된 이 스트림의 요소로 구성된 스트림을 반환합니다.
객체[] toArray() 이 스트림의 요소를 포함하는 배열을 반환합니다.
A[] toArray(IntFunction 생성기) 제공된 생성기 함수를 사용하여 반환된 배열과 분할된 실행 또는 크기 조정에 필요할 수 있는 추가 배열을 할당하여 이 스트림의 요소가 포함된 배열을 반환합니다.

Java 예제: Stream을 사용하지 않고 컬렉션 필터링

다음 예에서는 스트림을 사용하지 않고 데이터를 필터링합니다. 이 접근 방식은 스트림 패키지가 출시되기 전에 사용되었습니다.

엑셀 날짜 차이
 import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); List productPriceList = new ArrayList(); for(Product product: productsList){ // filtering data of list if(product.price<30000){ productpricelist.add(product.price); adding price to a productpricelist } system.out.println(productpricelist); displaying data < pre> <p> <strong>Output:</strong> </p> <pre> [25000.0, 28000.0, 28000.0] </pre> <hr> <h3>Java Stream Example: Filtering Collection by using Stream</h3> <p>Here, we are filtering data by using stream. You can see that code is optimized and maintained. Stream provides fast execution.</p> <pre> import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); List productPriceList2 =productsList.stream() .filter(p -&gt; p.price &gt; 30000)// filtering data .map(p-&gt;p.price) // fetching price .collect(Collectors.toList()); // collecting as list System.out.println(productPriceList2); } } </pre> <p> <strong>Output:</strong> </p> <pre> [90000.0] </pre> <hr> <h3>Java Stream Iterating Example</h3> <p>You can use stream to iterate any number of times. Stream provides predefined methods to deal with the logic you implement. In the following example, we are iterating, filtering and passed a limit to fix the iteration.</p> <pre> import java.util.stream.*; public class JavaStreamExample { public static void main(String[] args){ Stream.iterate(1, element-&gt;element+1) .filter(element-&gt;element%5==0) .limit(5) .forEach(System.out::println); } } </pre> <p> <strong>Output:</strong> </p> <pre> 5 10 15 20 25 </pre> <hr> <h3>Java Stream Example: Filtering and Iterating Collection</h3> <p>In the following example, we are using filter() method. Here, you can see code is optimized and very concise.</p> <pre> import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // This is more compact approach for filtering data productsList.stream() .filter(product -&gt; product.price == 30000) .forEach(product -&gt; System.out.println(product.name)); } } </pre> <p> <strong>Output:</strong> </p> <pre> Dell Laptop </pre> <hr> <h3>Java Stream Example : reduce() Method in Collection</h3> <p>This method takes a sequence of input elements and combines them into a single summary result by repeated operation. For example, finding the sum of numbers, or accumulating elements into a list. </p> <p>In the following example, we are using reduce() method, which is used to sum of all the product prices.</p> <pre> import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // This is more compact approach for filtering data Float totalPrice = productsList.stream() .map(product-&gt;product.price) .reduce(0.0f,(sum, price)-&gt;sum+price); // accumulating price System.out.println(totalPrice); // More precise code float totalPrice2 = productsList.stream() .map(product-&gt;product.price) .reduce(0.0f,Float::sum); // accumulating price, by referring method of Float class System.out.println(totalPrice2); } } </pre> <p> <strong>Output:</strong> </p> <pre> 201000.0 201000.0 </pre> <hr> <h3>Java Stream Example: Sum by using Collectors Methods</h3> <p>We can also use collectors to compute sum of numeric values. In the following example, we are using Collectors class and it?s specified methods to compute sum of all the product prices.</p> <pre> import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // Using Collectors&apos;s method to sum the prices. double totalPrice3 = productsList.stream() .collect(Collectors.summingDouble(product-&gt;product.price)); System.out.println(totalPrice3); } } </pre> <p> <strong>Output:</strong> </p> <pre> 201000.0 </pre> <hr> <h3>Java Stream Example: Find Max and Min Product Price</h3> <p>Following example finds min and max product price by using stream. It provides convenient way to find values without using imperative approach.</p> <pre> import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // max() method to get max Product price Product productA = productsList.stream().max((product1, product2)-&gt;product1.price &gt; product2.price ? 1: -1).get(); System.out.println(productA.price); // min() method to get min Product price Product productB = productsList.stream().min((product1, product2)-&gt;product1.price &gt; product2.price ? 1: -1).get(); System.out.println(productB.price); } } </pre> <p> <strong>Output:</strong> </p> <pre> 90000.0 25000.0 </pre> <hr> <h3>Java Stream Example: count() Method in Collection</h3> <pre> import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // count number of products based on the filter long count = productsList.stream() .filter(product-&gt;product.price<30000) .count(); system.out.println(count); } < pre> <p> <strong>Output:</strong> </p> <pre> 3 </pre> <p>stream allows you to collect your result in any various forms. You can get you result as set, list or map and can perform manipulation on the elements.</p> <hr> <h3>Java Stream Example : Convert List into Set</h3> <pre> import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // Converting product List into Set Set productPriceList = productsList.stream() .filter(product-&gt;product.price product.price) .collect(Collectors.toSet()); // collect it as Set(remove duplicate elements) System.out.println(productPriceList); } } </pre> <p> <strong>Output:</strong> </p> <pre> [25000.0, 28000.0] </pre> <hr> <h3>Java Stream Example : Convert List into Map</h3> <pre> import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // Converting Product List into a Map Map productPriceMap = productsList.stream() .collect(Collectors.toMap(p-&gt;p.id, p-&gt;p.name)); System.out.println(productPriceMap); } } </pre> <p> <strong>Output:</strong> </p> <pre> {1=HP Laptop, 2=Dell Laptop, 3=Lenevo Laptop, 4=Sony Laptop, 5=Apple Laptop} </pre> <hr> <h3>Method Reference in stream</h3> <pre> import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } public int getId() { return id; } public String getName() { return name; } public float getPrice() { return price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); List productPriceList = productsList.stream() .filter(p -&gt; p.price &gt; 30000) // filtering data .map(Product::getPrice) // fetching price by referring getPrice method .collect(Collectors.toList()); // collecting as list System.out.println(productPriceList); } } </pre> <p> <strong>Output:</strong> </p> <pre> [90000.0] </pre> <hr></30000)></pre></30000){>

Java 스트림 예: 스트림을 사용하여 컬렉션 필터링

여기서는 스트림을 사용하여 데이터를 필터링합니다. 코드가 최적화되어 유지관리되는 것을 볼 수 있습니다. Stream은 빠른 실행을 제공합니다.

 import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); List productPriceList2 =productsList.stream() .filter(p -&gt; p.price &gt; 30000)// filtering data .map(p-&gt;p.price) // fetching price .collect(Collectors.toList()); // collecting as list System.out.println(productPriceList2); } } 

산출:

 [90000.0] 

Java 스트림 반복 예제

스트림을 사용하여 원하는 만큼 반복할 수 있습니다. Stream은 구현하는 논리를 처리하기 위해 미리 정의된 메서드를 제공합니다. 다음 예에서는 반복을 수정하기 위해 반복, 필터링 및 제한을 전달합니다.

 import java.util.stream.*; public class JavaStreamExample { public static void main(String[] args){ Stream.iterate(1, element-&gt;element+1) .filter(element-&gt;element%5==0) .limit(5) .forEach(System.out::println); } } 

산출:

 5 10 15 20 25 

Java 스트림 예: 컬렉션 필터링 및 반복

다음 예에서는 filter() 메서드를 사용하고 있습니다. 여기에서 코드가 최적화되고 매우 간결한 것을 볼 수 있습니다.

 import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // This is more compact approach for filtering data productsList.stream() .filter(product -&gt; product.price == 30000) .forEach(product -&gt; System.out.println(product.name)); } } 

산출:

 Dell Laptop 

Java 스트림 예: 컬렉션의 Reduce() 메서드

이 방법은 일련의 입력 요소를 가져와 반복 작업을 통해 단일 요약 결과로 결합합니다. 예를 들어, 숫자의 합을 찾거나 요소를 목록에 누적합니다.

다음 예에서는 모든 제품 가격을 합산하는 데 사용되는 Reduce() 메서드를 사용합니다.

 import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // This is more compact approach for filtering data Float totalPrice = productsList.stream() .map(product-&gt;product.price) .reduce(0.0f,(sum, price)-&gt;sum+price); // accumulating price System.out.println(totalPrice); // More precise code float totalPrice2 = productsList.stream() .map(product-&gt;product.price) .reduce(0.0f,Float::sum); // accumulating price, by referring method of Float class System.out.println(totalPrice2); } } 

산출:

 201000.0 201000.0 

Java 스트림 예: 수집기 메서드를 사용하여 합계

또한 수집기를 사용하여 숫자 값의 합계를 계산할 수도 있습니다. 다음 예에서는 Collectors 클래스를 사용하고 있으며 모든 제품 가격의 합계를 계산하기 위해 지정된 메서드를 사용합니다.

 import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // Using Collectors&apos;s method to sum the prices. double totalPrice3 = productsList.stream() .collect(Collectors.summingDouble(product-&gt;product.price)); System.out.println(totalPrice3); } } 

산출:

 201000.0 

Java 스트림 예: 최대 및 최소 제품 가격 찾기

다음 예는 스트림을 사용하여 최소 및 최대 제품 가격을 찾습니다. 명령형 접근 방식을 사용하지 않고도 값을 찾는 편리한 방법을 제공합니다.

 import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // max() method to get max Product price Product productA = productsList.stream().max((product1, product2)-&gt;product1.price &gt; product2.price ? 1: -1).get(); System.out.println(productA.price); // min() method to get min Product price Product productB = productsList.stream().min((product1, product2)-&gt;product1.price &gt; product2.price ? 1: -1).get(); System.out.println(productB.price); } } 

산출:

 90000.0 25000.0 

Java 스트림 예: 컬렉션의 count() 메서드

 import java.util.*; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // count number of products based on the filter long count = productsList.stream() .filter(product-&gt;product.price<30000) .count(); system.out.println(count); } < pre> <p> <strong>Output:</strong> </p> <pre> 3 </pre> <p>stream allows you to collect your result in any various forms. You can get you result as set, list or map and can perform manipulation on the elements.</p> <hr> <h3>Java Stream Example : Convert List into Set</h3> <pre> import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // Converting product List into Set Set productPriceList = productsList.stream() .filter(product-&gt;product.price product.price) .collect(Collectors.toSet()); // collect it as Set(remove duplicate elements) System.out.println(productPriceList); } } </pre> <p> <strong>Output:</strong> </p> <pre> [25000.0, 28000.0] </pre> <hr> <h3>Java Stream Example : Convert List into Map</h3> <pre> import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // Converting Product List into a Map Map productPriceMap = productsList.stream() .collect(Collectors.toMap(p-&gt;p.id, p-&gt;p.name)); System.out.println(productPriceMap); } } </pre> <p> <strong>Output:</strong> </p> <pre> {1=HP Laptop, 2=Dell Laptop, 3=Lenevo Laptop, 4=Sony Laptop, 5=Apple Laptop} </pre> <hr> <h3>Method Reference in stream</h3> <pre> import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } public int getId() { return id; } public String getName() { return name; } public float getPrice() { return price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); List productPriceList = productsList.stream() .filter(p -&gt; p.price &gt; 30000) // filtering data .map(Product::getPrice) // fetching price by referring getPrice method .collect(Collectors.toList()); // collecting as list System.out.println(productPriceList); } } </pre> <p> <strong>Output:</strong> </p> <pre> [90000.0] </pre> <hr></30000)>

스트림을 사용하면 다양한 형태로 결과를 수집할 수 있습니다. 결과를 세트, 목록 또는 맵으로 얻을 수 있으며 요소에 대한 조작을 수행할 수 있습니다.


Java 스트림 예제: 목록을 집합으로 변환

 import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // Converting product List into Set Set productPriceList = productsList.stream() .filter(product-&gt;product.price product.price) .collect(Collectors.toSet()); // collect it as Set(remove duplicate elements) System.out.println(productPriceList); } } 

산출:

 [25000.0, 28000.0] 

Java 스트림 예제: 목록을 맵으로 변환

 import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); // Converting Product List into a Map Map productPriceMap = productsList.stream() .collect(Collectors.toMap(p-&gt;p.id, p-&gt;p.name)); System.out.println(productPriceMap); } } 

산출:

 {1=HP Laptop, 2=Dell Laptop, 3=Lenevo Laptop, 4=Sony Laptop, 5=Apple Laptop} 

스트림의 메소드 참조

 import java.util.*; import java.util.stream.Collectors; class Product{ int id; String name; float price; public Product(int id, String name, float price) { this.id = id; this.name = name; this.price = price; } public int getId() { return id; } public String getName() { return name; } public float getPrice() { return price; } } public class JavaStreamExample { public static void main(String[] args) { List productsList = new ArrayList(); //Adding Products productsList.add(new Product(1,&apos;HP Laptop&apos;,25000f)); productsList.add(new Product(2,&apos;Dell Laptop&apos;,30000f)); productsList.add(new Product(3,&apos;Lenevo Laptop&apos;,28000f)); productsList.add(new Product(4,&apos;Sony Laptop&apos;,28000f)); productsList.add(new Product(5,&apos;Apple Laptop&apos;,90000f)); List productPriceList = productsList.stream() .filter(p -&gt; p.price &gt; 30000) // filtering data .map(Product::getPrice) // fetching price by referring getPrice method .collect(Collectors.toList()); // collecting as list System.out.println(productPriceList); } } 

산출:

 [90000.0]