源上的一系列操作,其中操作包括中间操作和终端操作
中间操作如filter、maptoint
终端操作如count ,sum,foreach
创建流
Stream.of()
Stream.builder()
Stream.generate()
-
boolean allMatch(Predicate<? super T> predicate)
返回此流的所有元素是否与提供的谓词匹配。
@Test
public void testStreamAllMatch() {
boolean flag = Stream.of(1, 2, 3).allMatch(item -> item == 1); //false
flag = Stream.of(1, 2, 3).allMatch(item -> item < 4); //true
}
2.boolean anyMatch(Predicate<? super T> predicate)
返回此流的任意一个元素是否与提供的谓词匹配。(一个匹配即可)
@Test
public void testStreamAnyMatch() {
boolean flag = Stream.of(1, 2, 3).anyMatch(item -> item == 1);
System.out.println(flag) //true
flag = Stream.of(1, 2, 3).anyMatch(item -> item < 1);
System.out.println(flag); //false
}
3.collect(Collector<? super T,A,R> collector)
collect(Supplier supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner)
@Test
public void testStreamCollect() {
List list = Stream.of(1,2,3,4).collect(Collectors.toList());
Set set = Stream.of(1,2,3,4).collect(Collectors.toSet());
/**- 主键不能有重复
/
Map<Integer, Integer> map = Stream.of(1,2,3,4).collect(Collectors.toMap(item->item,item->item+1)); //<1,2><2,3><3,4><4,5>
/* - 主键重复时抛出异常
*/
try {
map = Stream.of(1,1,3,4).collect(Collectors.toMap(item->item,item->item+1));
} catch (Exception e) {
e.printStackTrace();
//java.lang.IllegalStateException: Duplicate key 2
}
/**
- 主键重复时,取值策略,本例是取新值
*/
map = Stream.of(1,1,3,4).collect(Collectors.toMap(item->item,item->item+1,(oldValue,newValue)->newValue));
System.out.println(map);
}
- 主键不能有重复
4.filter(Predicate<? super T> predicate)
返回由与此给定谓词匹配的此流的元素组成的流。
@Test
public void tsetStreamFilter() {
//filter过滤大于1的元素,distinct取不重复的元素,limit取前4个元素,count取数量
Stream.of(1,2,3,4,4,5,6,7,8).filter(item->item>1).distinct().limit(4).count();
}
5.sorted(Comparator<? super T> comparator)
sorted()
@Test
public void testStreamSorted() {
//指定排序规则
List list = Stream.of(1,4,3,5).sorted(new Comparator() {
@Override
public int compare(Integer o1, Integer o2) {
return o1-o2;
}
}).collect(Collectors.toList()); //(1,3,4,5)
//自然排序规则
list = Stream.of(1,4,3,5).sorted().collect(Collectors.toList()); (1,3,4,5)
}
reference:http://www.matools.com/api/java8