java8的stream用戶java
數據準備:數組
public class Dish { public String name; //菜的名稱 public Boolean vegetaian; //是否爲素 public Integer calories; //卡路里 public Type type; //類型(肉 魚 其餘) public Dish() { } public Dish(String name, Boolean vegetaian, Integer calories, Type type) { this.name = name; this.vegetaian = vegetaian; this.calories = calories; this.type = type; } public enum Type {MEAT, FISH, OTHER} //肉 魚 其餘 }
public class DishList { public static List<Dish> getDishList() { List<Dish> dishList = Arrays.asList( new Dish("pork", false, 800, Dish.Type.MEAT), new Dish("beef", false, 700, Dish.Type.MEAT), new Dish("chicken", false, 400, Dish.Type.MEAT), new Dish("french fries", true, 530, Dish.Type.OTHER), new Dish("rice", true, 350, Dish.Type.OTHER), new Dish("season fruit", true, 120, Dish.Type.OTHER), new Dish("pizza", true, 550, Dish.Type.OTHER), new Dish("prawns", false, 300, Dish.Type.FISH), new Dish("salmon", false, 450, Dish.Type.FISH) ); return dishList; } }
1:filterapp
/** * filter 過濾結果爲true的 * 過濾「calories:卡路里」小於500的 */ @Test public void filter() { List<Dish> dishList = DishList.getDishList(); List<Dish> collect = dishList.stream().filter(dish -> dish.getCalories() < 500).collect(Collectors.toList()); collect.forEach(System.out::println); }
2:distinctide
/** * 去重:過濾元素相同的 */ @Test public void distinct() { List<Integer> list = Arrays.asList(1, 2, 3, 4, 1, 2); list.stream().distinct().forEach(System.out::println); }
3: skipui
/** * skip 跳過前n個 */ @Test public void skip() { List<Dish> dishList = DishList.getDishList(); dishList.stream().skip(5).forEach(System.out::println); }
4: limitthis
/** * limit 只保留前n個 */ @Test public void limit() { List<Dish> dishList = DishList.getDishList(); dishList.stream().limit(5).forEach(System.out::println); }
5: mapspa
/** * map 映射 */ @Test public void map() { List<Dish> dishList = DishList.getDishList(); Function<Dish, String> function1 = dish -> dish.getName() + ","; //轉換的結果能夠爲任意類型與形式 Function<Dish, String> function2 = Dish::getName; List<String> collect = dishList.stream().map(function1).collect(Collectors.toList()); collect.forEach(System.out::println); }
6: flatMapcode
/** * flatMap:扁平化 * 獲取每個元素,並去重
對hello,world分割去重 */
@Test
public void filter3() {
String[] words = {"hello", "world"};
// 將words換成流,stream中有 "hello","world" 兩個元素
Stream<String> stream = Arrays.stream(words);
// 將stream中每一個元素映射成「字符串數組」 ,stream1中有「h,e,l,l,o」,"w,o,r,l,d"
Stream<String[]> stream1 = stream.map(item -> item.split(""));
// 將流中的每一個值都換成另外一個流,而後把全部的流連接成1個流(將stream1映射成「h,e,l,l,o,w,o,r,l,d」)
Stream<String> stream2 = stream1.flatMap(Arrays::stream);
stream2.distinct().forEach(System.out::println);
}
Matchblog
7:allMatchip
/** * 全匹配 * 全部的dish的calories都<400嗎? */ @Test public void allMatch() { List<Dish> dishList = DishList.getDishList(); boolean b = dishList.stream().allMatch(item -> item.getCalories() < 400); System.out.println(b); }
8:anyMatch
/**
* 存在一個匹配
* 至少1個dish的calories都<400嗎?
*/
@Test
public void anyMatch() {
List<Dish> dishList = DishList.getDishList();
boolean b = dishList.stream().anyMatch(item -> item.getCalories() < 400);
System.out.println(b);
}
9:noneMatch
/** * 不存在匹配 * 全部的dish的calories都不<400嗎? */ @Test public void noneMatch() { List<Dish> dishList = DishList.getDishList(); boolean b = dishList.stream().noneMatch(item -> item.getCalories() < 400); System.out.println(b); }
Find
10:findAny
@Test public void findAny() { List<Dish> dishList = DishList.getDishList(); Dish dish = dishList.stream().findAny().orElse(new Dish()); System.out.println(dish); }
11:findFirst
@Test public void findFirst() { List<Dish> dishList = DishList.getDishList(); Dish dish = dishList.stream().findFirst().orElse(new Dish()); System.out.println(dish); }
Reduce 規約(將流中的元素組合,規約成一個值)
12:reduce
@Test
public void reduce1() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
IntBinaryOperator operator = (s1, s2) -> s1 + s2;
OptionalInt reduce = list.stream().mapToInt(Integer::intValue).reduce(operator);
int asInt = reduce.getAsInt();
System.out.println(asInt);
//IntBinaryOperator 的 int applyAsInt(int left, int right); 方法,接受兩個參數
//mapToInt(Integer::intValue) 將int值拆箱
//getAsInt 從Optional取出值(若是值不存在則拋出異常) 使用 int asInt = reduce.orElse(0); 獲取值,或者使用isPresient判斷再取值
}
13:reduce
@Test public void reduce2() { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6); IntBinaryOperator operator = (s1, s2) -> s1 + s2; int reduce = list.stream().mapToInt(Integer::intValue).reduce(0,operator); //使用默認值
//int reduce = list.stream().mapToInt(Integer::intValue).reduce(0,Integer::sum) //Integer::sum 求和 Integet::max 最大值 Integer::min 最小值
System.out.println(reduce);
}
14:boxed
/** * 包裝與拆箱 */ @Test public void boxed() { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6); IntStream intStream = list.stream().mapToInt(Integer::intValue); //拆箱 Stream<Integer> boxed = intStream.boxed(); //包裝 List<Integer> collect = boxed.collect(Collectors.toList()); }
Optional (待完善)
15:Optional
/** * Optional 包裝 */ @Test public void optional() { //包含元素爲null的Optional Optional empty = Optional.empty(); boolean present = empty.isPresent(); // false //包含元素必須不爲null Optional<String> of = Optional.of("optional"); //包含元素爲null調用 empty()方法,不爲null調用 of()方法 Optional<String> optional = Optional.ofNullable("optional"); }
Collectors
16:toList
/** * toList
* 篩選「vegetaian」,-> list */ @Test public void toList() { List<Dish> dishList = DishList.getDishList(); List<Dish> collect = dishList.stream().filter(Dish::getVegetaian).collect(Collectors.toList()); }
17:toSet
/** * toSet
*將dish -> name->set */ @Test public void toSet() { List<Dish> dishList = DishList.getDishList(); Set<String> collect = dishList.stream().map(Dish::getName).collect(Collectors.toSet()); }
18:toMap
/** * toMap
* key:name value:dish */ @Test public void toMap() { List<Dish> dishList = DishList.getDishList(); Map<String, Dish> collect = dishList.stream().collect(Collectors.toMap(Dish::getName, Function.identity())); }
19:toConcurrentMap
/** * toConcurrentMap * key:name value:自身 ->存放到ConcurrentMap中 */ @Test public void toConcurrentMap() { List<Dish> dishList = DishList.getDishList(); ConcurrentMap<String, Dish> collect = dishList.stream().collect(Collectors.toConcurrentMap(Dish::getName, Function.identity())); }
20:averaging
/** * 平均值
* 返回的都是double類型,區別在「參數」限制 */ @Test public void averaging() { List<Dish> dishList = DishList.getDishList(); Double aInt = dishList.stream().collect(Collectors.averagingInt(Dish::getCalories)); Double aDouble = dishList.stream().collect(Collectors.averagingDouble(Dish::getCalories)); Double aLong = dishList.stream().collect(Collectors.averagingLong(Dish::getCalories)); }
21:collectingAndThen
/** * 附加動做 * collectingAndThen(Collector<T,A,R> downstream,Function<R,RR> finisher) * Collector 執行的結果做爲 Function 的入參 * 備註:Collectors調用的方法返回的便是Collector類型 */ @Test public void collectingAndThen() { List<Dish> dishList = DishList.getDishList(); String collect = dishList.stream().collect(Collectors.collectingAndThen(Collectors.averagingInt(Dish::getCalories), item -> "結果爲:" + item)); System.out.println(collect); }
22:unmodifiableList
/** * 只讀 * */ @Test public void unmodifiableList() { List<Dish> dishList = DishList.getDishList(); List<Dish> collect = dishList.stream().collect(Collectors.collectingAndThen(Collectors.toList(),Collections::unmodifiableList)); }
23: