Java8中Stream API如何使用


本篇文章为大家展示了Java8中Stream API如何使用,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。
首先创建一个对象publicclassEmployee{

privateintid;
privateString name;
privateintage;
privatedoublesalary;
privateStatus status;

publicenumStatus {
FREE, BUSY, VOCATION;
}

publicEmployee(){
}

publicEmployee(String name){
this.name = name;
}

publicEmployee(String name, intage){
this.name = name;
this.age = age;
}

publicEmployee(intid, String name, intage, doublesalary){
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}

publicEmployee(intid, String name, intage, doublesalary, Status status){
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
this.status = status;
}
//省略get,set等。。。
}随便初始化一些数据List empList = Arrays.asList(newEmployee(102, “李四”, 59, 6666.66, Status.BUSY),
newEmployee(101, “张三”, 18, 9999.99, Status.FREE), newEmployee(103, “王五”, 28, 3333.33, Status.VOCATION),
newEmployee(104, “赵六”, 8, 7777.77, Status.BUSY), newEmployee(104, “赵六”, 8, 7777.77, Status.FREE),
newEmployee(104, “赵六”, 8, 7777.77, Status.FREE), newEmployee(105, “田七”, 38, 5555.55, Status.BUSY));
中间操作根据条件筛选 filter/**
* 接收Lambda, 从流中排除某些元素。
*/@Test
voidtestFilter(){
empList.stream().filter((e) -> {
returne.getSalary() >= 5000;
}).forEach(System.out::println);
}跳过流的前n个元素 skip/**
* 跳过元素,返回一个扔掉了前n个元素的流。
*/
@Test
void testSkip() {
empList.stream().filter((e) -> e.getSalary() >= 5000).skip(2).forEach(System.out::println);
}去除重复元素 distinct/**
* 筛选,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
*/
@Test
void testDistinct() {
empList.stream().distinct().forEach(System.out::println);
}截取流的前n个元素 limit/**
* 截断流,使其元素不超过给定数量。
*/
@Test
void testLimit() {
empList.stream().filter((e) -> {
returne.getSalary() >= 5000;
}).limit(3).forEach(System.out::println);
}映射 map/**
* 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素
*/
@Test
void testMap() {
empList.stream().map(e -> e.getName()).forEach(System.out::println);

empList.stream().map(e -> {
empList.forEach(i -> {
i.setName(i.getName() + “111”);
});
returne;
}).collect(Collectors.toList());
}自然排序 sorted/**
* 产生一个新流,其中按自然顺序排序
*/
@Test
void testSorted() {
empList.stream().map(Employee::getName).sorted().forEach(System.out::println);
}自定义排序 sorted(Comparator comp)/**
* 产生一个新流,其中按自然顺序排序
*/
@Test
void testSortedComparator() {
empList.stream().sorted((x, y) -> {
if(x.getAge() == y.getAge()) {
returnx.getName().compareTo(y.getName());
} else{
returnInteger.compare(x.getAge(), y.getAge());
}
}).forEach(System.out::println);
}
最终操作是否匹配任一元素 anyMatch/**
* 检查是否至少匹配一个元素
*/
@Test
voidtestAnyMatch() {
boolean b = empList.stream().anyMatch((e) -> e.getStatus().equals(Status.BUSY));
System.out.println(“boolean is : “+ b);
}是否匹配所有元素 allMatch/**
* 检查是否匹配所有元素
*/
@Test
voidtestAllMatch() {
boolean b = empList.stream().allMatch((e) -> e.getStatus().equals(Status.BUSY));
System.out.println(“boolean is : “+ b);
}/**
* 检查是否没有匹配的元素
*/
@Test
voidtestNoneMatch() {
boolean b = empList.stream().noneMatch((e) -> e.getStatus().equals(Status.BUSY));
System.out.println(“boolean is : “+ b);
}返回第一个元素 findFirst/**
* 返回第一个元素
*/
@Test
voidtestFindFirst() {
Optional op = empList.stream().sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
.findFirst();
if(op.isPresent()) {
System.out.println(“first employee name is : “+ op.get().getName().toString());
}
}
/**
* 返回当前流中的任意元素
*/
@Test
voidtestFindAny() {
Optional op = empList.stream().sorted((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()))
.findAny();
if(op.isPresent()) {
System.out.println(“any employee name is : “+ op.get().getName().toString());
}
}
返回流的总数 count/**
* 返回流中元素的总个数
*/
@Test
voidtestCount() {
longcount = empList.stream().filter((e) -> e.getStatus().equals(Status.FREE)).count();
S 香港云主机ystem.out.println(“Count is : “+ count);
}返回流中的最大值 max/**
* 返回流中最大值
*/
@Test
voidtestMax(){
Optional op = empList.stream().map(Employee::getSalary).max(Double::compare);
System.out.println(op.get());
}
返回流中的最小值 min/**
* 返回流中最小值
*/
@Test
voidtestMin() {
Optional op2 = empList.stream().min((e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary()));
System.out.println(op2.get());
}
归约 reduce
归约是将集合中的所有元素经过指定运算,折叠成一个元素输出/**
* 可以将流中元素反复结合起来,得到一个值。返回T
*/
@Test
voidtestReduce(){
Optional op = empList.stream().map(Employee::getSalary).reduce(Double::sum);

System.out.println(op.get());
}

/**
* 可以将流中元素反复结合起来,得到一个值,返回Optional
*/
@Test
voidtestReduce1(){
Optional sum = empList.stream().map(Employee::getName).flatMap(Java8Stream::filterCharacter)
.map((ch) -> {
if(ch.equals(‘六’))
return1;
else
return0;
}).reduce(Integer::sum);
System.out.println(sum.get());
}
将元素收集到 list 里 Collectors.toList()/**
* 把流中的元素收集到list里。
*/
@Test
void testCollectorsToList() {
List list= empList.stream().map(Employee::getName).collect(Collectors.toList());
list.forEach(System.out::println);
}
将元素收集到 set 里 Collectors.toSet()/**
* 把流中的元素收集到set里。
*/
@Test
void testCollectorsToSet() {
Set list= empList.stream().map(Employee::getName).collect(Collectors.toSet());
list.forEach(System.out::println);
}
把流中的元素收集到新创建的集合里Collectors.toCollection(HashSet::new)/**
* 把流中的元素收集到新创建的集合里。
*/
@Test
void testCollectorsToCollection() {
HashSet hs = empList.stream().map(Employee::getName).collect(Collectors.toCollection(HashSet::new));
hs.forEach(System.out::println);
}
根据比较器选择最大值 Collectors.maxBy()/**
* 根据比较器选择最大值。
*/
@Test
voidtestCollectorsMaxBy(){
Optional max = empList.stream().map(Employee::getSalary).collect(Collectors.maxBy(Double::compare));
System.out.println(max.get());
}
根据比较器选择最小值 Collectors.minBy()/**
* 根据比较器选择最小值。
*/
@Test
voidtestCollectorsMinBy(){
Optional max = empList.stream().map(Employee::getSalary).collect(Collectors.minBy(Double::compare));
System.out.println(max.get());
}
对流中元素的某个字段求和 Collectors.summingDouble()/**
* 对流中元素的整数属性求和。
*/
@Test
voidtestCollectorsSummingDouble(){
Double sum = empList.stream().collect(Collectors.summingDouble(Employee::getSalary));
System.out.println(sum);
}对流中元素的某个字段求平均值 Collectors.averagingDouble()/**
* 计算流中元素Integer属性的平均值。
*/
@Test
voidtestCollectorsAveragingDouble(){
Double avg = empList.stream().collect(Collectors.averagingDouble(Employee::getSalary));
System.out.println(avg);
}分组,类似sql的 group byCollectors.groupingBy/**
* 分组
*/
@Test
voidtestCollectorsGroupingBy(){
Map> map= empList.stream().collect(Collectors.groupingBy(Employee::getStatus));

System.out.println(map);
}
/**
* 多级分组
*/
@Test
voidtestCollectorsGroupingBy1(){
Map>> map= empList.stream()
.collect(Collectors.groupingBy(Employee::getStatus, Collectors.groupingBy((e) -> {
if(e.getAge() >= 60)
return”老年”;
elseif(e.getAge() >= 35)
return”中年”;
else
return”成年”;
})));
System.out.println(map);
}
字符串拼接 Collectors.joining()/**
* 字符串拼接
*/
@Test
voidtestCollectorsJoining(){
String str = empList.stream().map(Employee::getName).collect(Collectors.joining(“,”, “—-“, “—-“));
System.out.println(str);
}publicstaticStream filterCharacter(String str) {

List list= newArrayList();
for(Character ch : str.toCharArray()) {
list.add(ch);
}
returnlist.stream();
}
上述内容就是Java8中Stream API如何使用,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注开发云行业资讯频道。

相关推荐: hadoop配置名称节点HA原理

ArchitectureIn a typical HA clusiter, two separate machines are configured as NameNodes. At any point in time, exactly one of the …

免责声明:本站发布的图片视频文字,以转载和分享为主,文章观点不代表本站立场,本站不承担相关法律责任;如果涉及侵权请联系邮箱:360163164@qq.com举报,并提供相关证据,经查实将立刻删除涉嫌侵权内容。

(0)
打赏 微信扫一扫 微信扫一扫
上一篇 07/30 16:52
下一篇 07/30 16:52

相关推荐