1、建立Stream
2、Stream篩選和切片
3、Stream映射
4、Stream排序
5、Stream查找與匹配
6、Stream約與收集歸
7、Stream約操練
1、建立Stream
package com.stream.api1;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.junit.Test;
/**
* 一 、 Stream 的三個操作步調 1、建立Stream 2、中級操作 3、終止操作(終端操作)
*
* @author Administrator
*
*/
public class TestStreamAPI1 {
// 建立Stream
@Test
public void test1() {
// 1、可以經由過程Collection 系列調集供給的stream()或parallelStream()
List<String> list = new ArrayList<String>();
Stream<String> stream1 = list.stream();
// 2、經由過程Arrays中的靜態方式stream()獲取數組流
Employee[] ems = new Employee[10];
Stream<Employee> stream2 = Arrays.stream(ems);
// 3、經由過程Stream類中的靜態方式of()
Stream<String> stream3 = Stream.of("aa", "bb", "cc", "dd");
// 4、建立無限流
Stream<Integer> stream4 = Stream.iterate(0, x -> x + 2);
// stream4.forEach(System.out::println);
stream4.limit(10).forEach(System.out::println);
// 生當作
Stream.generate(() -> Math.random()).limit(5).forEach(System.out::println);
}
}
2、Stream篩選和切片
package com.stream.api2;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Stream;
import org.junit.Test;
import com.stream.api1.Employee;
/**
* 一 、 Stream 的三個操作步調 1、建立Stream 2、中級操作 3、終止操作(終端操作)
*
* @author Administrator
*
*/
public class TestStreamAPI2 {
List<Employee> employees = Arrays.asList(new Employee("張三", 12, 1200.99), new Employee("小明", 15, 4500.99),
new Employee("小麗", 16, 5500.99), new Employee("王二", 32, 1100.99), new Employee("二虎", 22, 9825.99),
new Employee("李靜", 18, 4502.99), new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99),
new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99));
// 中心操作
/**
* 篩選與切片 filter —— 領受Lambda,從流中解除某些元素 limit —— 截斷流,使其元素不跨越給定命量。 skip(n) ——
* 跳過元素,返回一個扔失落了前n個元素的流。若流中元素不足n個,則返回一個空流。與limit(n)互補 distinct ——
* 篩選,經由過程流所生當作元素的hashCode()和equals()去除反復元素
*
*
* 注重:利用distinct去重需要重寫hashcode和equals方式
*/
// 內部迭代:迭代操作有Stream API完當作。
@Test
public void test1() {
// 中心操作:不會執行任何操作
Stream<Employee> stream1 = employees.stream().filter((e) -> {
System.out.println("Stream API中心操作");
return e.getAge() > 17;
});
// 終止操作:一次性執行全數內容,即“惰性求值”
stream1.forEach(System.out::println);
}
// 外部迭代
@Test
public void test2() {
Iterator<Employee> it = employees.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
// 短路,limit一旦找到合適的數據將不再繼續執行,必然水平上提高了機能
@Test
public void test3() {
employees.stream().filter((e) -> {
System.out.println("短路!");
return e.getSalary() > 5000;
}).limit(2).forEach(System.out::println);
;
}
@Test
public void test4() {
employees.stream().filter((e) -> e.getSalary() > 1000).skip(2).limit(2).forEach(System.out::println);
;
}
@Test
public void test5() {
employees.stream().filter((e) -> e.getSalary() > 1000).skip(2).distinct().forEach(System.out::println);
;
}
}
/3、Stream映射
package com.stream.api3;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
import org.junit.Test;
import com.stream.api1.Employee;
public class TestStreamAPI3 {
List<Employee> employees = Arrays.asList(new Employee("張三", 12, 1200.99), new Employee("小明", 15, 4500.99),
new Employee("小麗", 16, 5500.99), new Employee("王二", 32, 1100.99), new Employee("二虎", 22, 9825.99),
new Employee("李靜", 18, 4502.99), new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99),
new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99));
/**
*
* 映射 map —— Lambda,將元素轉換當作其它形式或提守信息,領受一個函數作為參數,改函數會被應用到每個元素上, 并將其映射當作一個新的元素。
* flatMap —— 領受一個函數作為參數,將流中的每個值都換當作另一個流,然后把所有的流連城一個流。
*/
@Test
public void test6() {
List<String> list = Arrays.asList("aaa", "bbb", "bbb", "ddd");
list.stream().map((str) -> str.toUpperCase()).forEach(System.out::println);
System.out.println("---------------------------");
employees.stream().map(Employee::getName).forEach(System.out::println);
System.out.println("---------------------------");
Stream<Stream<Character>> stream = list.stream().map(TestStreamAPI3::filterCharacter);
stream.forEach((sm) -> {
sm.forEach(System.out::println);
});
System.out.println("---------------------------");
Stream<Character> stream2 = list.stream().flatMap(TestStreamAPI3::filterCharacter);
stream2.forEach(System.out::println);
}
public static Stream<Character> filterCharacter(String str) {// add(Object obj) addAll(collection coll)
List<Character> list = new ArrayList<>();
for (Character character : str.toCharArray()) {
list.add(character);
}
return list.stream();
}
}
4、Stream排序
package com.stream.api4;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import com.stream.api1.Employee;
public class TestStreamAPI4 {
List<Employee> employees = Arrays.asList(new Employee("張三", 12, 1200.99), new Employee("小明", 15, 4500.99),
new Employee("小麗", 16, 5500.99), new Employee("王二", 32, 1100.99), new Employee("二虎", 22, 9825.99),
new Employee("李靜", 18, 4502.99), new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99),
new Employee("小三", 17, 1469.99), new Employee("小三", 17, 1469.99));
/**
* 排序 sorted() —— 天然排序(Comparable) sorted(Comparater com) —— 心猿意馬制排序(Comparater)
*/
@Test
public void test1() {
List<String> list = Arrays.asList("ccc", "aaa", "bbb", "ddd", "eee");
list.stream().sorted().forEach(System.out::println);
System.out.println("--------------------------------------------");
employees.stream().sorted((e1, e2) -> {
if (e1.getAge() == e2.getAge()) {
return e1.getName().compareTo(e2.getName());
} else {
return Integer.compare(e1.getAge(), e2.getAge());
}
}).forEach(System.out::println);
}
}
5、Stream查找與匹配
package com.stream.api5;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.junit.Test;
import com.stream.api1.Employee;
import com.stream.api1.Employee.Status;
public class TestStreamAPI5 {
List<Employee> employees = Arrays.asList(new Employee("張三", 12, 1200.99, Status.BUSY),
new Employee("小明", 15, 4500.99, Status.BUSY), new Employee("小麗", 16, 5500.99, Status.BUSY),
new Employee("王二", 32, 1100.99, Status.FREE), new Employee("二虎", 22, 9825.99, Status.FREE),
new Employee("李靜", 18, 4502.99, Status.FREE), new Employee("小三", 17, 1469.99, Status.VOCATION),
new Employee("小三", 17, 1469.99, Status.VOCATION), new Employee("小三", 17, 1469.99, Status.VOCATION),
new Employee("小三", 17, 1469.99, Status.VOCATION));
/**
* 查找與匹配 allMatch —— 查抄是否平匹配所有元素 anyMatch —— 查抄是否至少匹配一個元素 noneMatch ——
* 查抄是否沒有匹配的元素 findFirst —— 返回第一個元素 findAny —— 返回當前流中的肆意元素 count —— 返回流中元素的總個數
* max —— 返回流中最大值 min —— 返回流中最小值
*/
@Test
public void test1() {
boolean b1 = employees.stream().allMatch(e -> e.getStatus().equals(Status.BUSY));
System.out.println(b1);
boolean b2 = employees.stream().anyMatch((e) -> e.getStatus().equals(Status.BUSY));
System.out.println(b2);
boolean b3 = employees.stream().noneMatch((e) -> e.getStatus().equals(Status.BUSY));
System.out.println(b3);
Optional<Employee> op1 = employees.stream().sorted((e1, e2) -> -Double.compare(e1.getSalary(), e2.getSalary()))
.findFirst();
System.out.println(op1.get());
Optional<Employee> op2 = employees.stream().filter((e) -> e.getStatus().equals(Status.FREE)).findAny();
System.out.println(op2.get());
Optional<Employee> op3 = employees.parallelStream().filter((e) -> e.getStatus().equals(Status.FREE)).findAny();
System.out.println(op3.get());
}
@Test
public void test2() {
Long count = employees.stream().count();
System.out.println(count);
Optional<Employee> op1 = employees.stream().max((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
System.out.println(op1.get());
Optional<Double> op2 = employees.stream().map(Employee::getSalary).max(Double::compare);
System.out.println(op2.get());
}
}
6、Stream約與收集歸
package com.stream.api6;
import java.util.Arrays;
import java.util.DoubleSummaryStatistics;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import org.junit.Test;
import com.stream.api1.Employee;
import com.stream.api1.Employee.Status;
public class TestStreamAPI6 {
List<Employee> employees = Arrays.asList(new Employee("張三", 12, 1200.99, Status.BUSY),
new Employee("小明", 15, 4500.99, Status.BUSY), new Employee("小麗", 16, 5500.99, Status.BUSY),
new Employee("王二", 32, 1100.99, Status.FREE), new Employee("二虎", 22, 9825.99, Status.FREE),
new Employee("李靜", 18, 4502.99, Status.FREE), new Employee("小三", 17, 1469.99, Status.VOCATION),
new Employee("小三", 17, 1469.99, Status.VOCATION), new Employee("小三", 17, 1469.99, Status.VOCATION),
new Employee("小三", 17, 1469.99, Status.VOCATION));
/**
* 歸約 reduce(T identity,BinaryOperator)/reduce(BinaryOperator) ——
* 可以將流中元素頻頻連系起來,獲得一個值
*/
@Test
public void test1() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
Integer sum = list.stream().reduce(0, (x, y) -> x + y);
System.out.println(sum);
System.out.println("-------------------------------------------");
Optional<Double> op1 = employees.stream().map(Employee::getSalary).reduce(Double::sum);
System.out.println(op1.get());
}
/**
* 收集 collect —— 將流轉換為其它形式,領受一個Collector接口的實現,用于給Stream中元素做匯總的方式
*/
@Test
public void test2() {
List<String> list = employees.stream().map(Employee::getName).collect(Collectors.toList());
list.forEach(System.out::println);
System.out.println("-----------------------");
Set<String> set = employees.stream().map(Employee::getName).collect(Collectors.toSet());
set.forEach(System.out::println);
System.out.println("-----------------------");
HashSet<String> hashSet = employees.stream().map(Employee::getName)
.collect(Collectors.toCollection(HashSet::new));
hashSet.forEach(System.out::println);
}
@Test
public void test3() {
// 總數
Long count = employees.stream().collect(Collectors.counting());
System.out.println(count);
System.out.println("-----------------------");
// 平均值
Double avg = employees.stream().collect(Collectors.averagingDouble(Employee::getSalary));
System.out.println(avg);
System.out.println("-----------------------");
// 總和
Double sum = employees.stream().collect(Collectors.summingDouble(Employee::getSalary));
System.out.println(sum);
System.out.println("-----------------------");
// 最大值
Optional<Employee> max = employees.stream()
.collect(Collectors.maxBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
System.out.println(max.get());
System.out.println("-----------------------");
// 最大值
Optional<Employee> min = employees.stream()
.collect(Collectors.minBy((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary())));
System.out.println(min.get());
}
// 分組
@Test
public void test4() {
Map<Status, List<Employee>> map = employees.stream().collect(Collectors.groupingBy(Employee::getStatus));
System.out.println(map);
}
// 多級分組
@Test
public void test5() {
Map<Status, Map<String, List<Employee>>> map = employees.stream()
.collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
if (e.getAge() < 16) {
return "青年";
} else if (e.getAge() < 18) {
return "中年";
} else {
return "老年";
}
})));
System.out.println(map);
}
// 分區
@Test
public void test6() {
Map<Boolean, List<Employee>> map = employees.stream()
.collect(Collectors.partitioningBy(e -> e.getSalary() > 5000));
System.out.println(map);
}
@Test
public void test7() {
DoubleSummaryStatistics collect = employees.stream().collect(Collectors.summarizingDouble(Employee::getSalary));
System.out.println(collect.getAverage());
System.out.println(collect.getCount());
System.out.println(collect.getMax());
System.out.println(collect.getMin());
System.out.println(collect.getSum());
}
@Test
public void test8() {
String str1 = employees.stream().map(Employee::getName).collect(Collectors.joining());
System.out.println(str1);
System.out.println("---------------------------------");
String str2 = employees.stream().map(Employee::getName).collect(Collectors.joining(","));
System.out.println(str2);
System.out.println("---------------------------------");
String str3 = employees.stream().map(Employee::getName).collect(Collectors.joining(",", "===", "==="));
System.out.println(str3);
}
}
7、Stream約操練
0 篇文章
如果覺得我的文章對您有用,請隨意打賞。你的支持將鼓勵我繼續創作!