foreach

list.forEach(System.out::println); 

map

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList()); 

filter

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// count empty strings
long count = strings.stream().filter(string -> string.isEmpty()).count(); 
List<UserInfo> list = new ArrayList<>();

UserInfo userInfo1 = new UserInfo();
userInfo1.setUserName("aa");
userInfo1.setCustomerPhone("123");
UserInfo userInfo2 = new UserInfo();
userInfo2.setUserName("bb");
userInfo2.setCustomerPhone("456");
UserInfo userInfo3 = new UserInfo();
userInfo3.setUserName("cc");
userInfo3.setCustomerPhone("789");

list.add(userInfo1);
list.add(userInfo2);
list.add(userInfo3);

// get Users with name bb
List<UserInfo> collect = list.stream().filter(userInfo -> "bb".equals(userInfo.getUserName())).collect(Collectors.toList());
// get the User with phone number 222
Optional<UserInfo> first = list.stream().filter(userInfo -> "222".equals(userInfo.getCustomerPhone())).findFirst(); 

limit

Random random = new Random();
random.ints().limit(10).forEach(System.out::println); 

sorted

Random random = new Random();
random.ints().limit(10).sorted().forEach(System.out::println); 

reduce

This method takes a sequence of input elements and combines them into a single summary result by repeated operation.

List<Product> productsList = new ArrayList<Product>();  
//Adding Products  
productsList.add(new Product(1,"HP Laptop",25000f));  
productsList.add(new Product(2,"Dell Laptop",30000f));  
productsList.add(new Product(3,"Lenevo Laptop",28000f));  
productsList.add(new Product(4,"Sony Laptop",28000f));  
productsList.add(new Product(5,"Apple Laptop",90000f));  
// This is more compact approach for filtering data  
Float totalPrice = productsList.stream()  
            .map(product->product.price)  
            .reduce(0.0f,(sum, price)->sum+price);   // accumulating price  
System.out.println(totalPrice);  
// More precise code   
float totalPrice2 = productsList.stream()  
        .map(product->product.price)  
        .reduce(0.0f,Float::sum);   // accumulating price, by referring method of Float class  
System.out.println(totalPrice2);   

Sum by using Collectors Methods

 double totalPrice3 = productsList.stream()  
            .collect(Collectors.summingDouble(product->product.price));   

max and min

 // max() method to get max Product price     
Product productA = productsList.stream()
        .max((product1, product2)->product1.price > product2.price ? 1: -1).get();    
System.out.println(productA.price);    
// min() method to get min Product price    
Product productB = productsList.stream()
        .min((product1, product2)->product1.price > product2.price ? 1: -1).get();    
System.out.println(productB.price);    

count

 long count = productsList.stream()  
                    .filter(product->product.price<30000)  
                    .count();   

Convert List into Set

Set<Float> productPriceSet = productsList.stream()  
        .filter(product->product.price < 30000)   // filter product on the base of price  
        .map(product->product.price)  
        .collect(Collectors.toSet());   // collect it as Set(remove duplicate elements) 

// Another method: Method Reference  
Set<Float> productPriceSet = productsList.stream()  
        .filter(product->product.price < 30000)    
        .map(Product::getPrice)  
        .collect(Collectors.toSet());  

Convert List into Map

Map<Integer,String> productPriceMap = productsList.stream()  
        .collect(Collectors.toMap(p->p.id, p->p.name));   

Convert List into HashMap

Map<Integer, Product> productHashMap = productsList.stream()
    .collect(HashMap::new, (m, v) -> m.put(v.getId(), m), HashMap::putAll); 

parallelStream

parallelStream is a replacement for stream parallel processor.

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// get the number of empty strings
long count = strings.parallelStream().filter(string -> string.isEmpty()).count(); 

flatMap

flatMap () method can convert each element of a stream to a stream, and then these streams are connected to a new stream. That is to say, it can make a stream from the origin stream elements to a new stream.

import java.util.stream.*;
import java.util.Arrays;

public class FlatMapDemo {

  public static void main(String[] args) {

    // 列表流
    List<Integer> list1 = Arrays.asList(1, 2, 3);
    List<Integer> list2 = Arrays.asList(4, 5, 6);
    List<List<Integer>> listofLists = Arrays.asList(list1, list2);
    
    // 使用 flatMap 把嵌套流展平
    Stream<Integer> flatStream = listofLists.stream()
                                      .flatMap(list -> list.stream());
                                      
    // 打印展平后的流
    flatStream.forEach(System.out::println);
  }
} 
Output:
1
2
3
4
5
6

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *

Catalogue