java8 array、list操作 汇【4】)- Java8 Lambda表达式 函数式编程
int tmp1 = 1; //包围类的成员变量
static int tmp2 = 2; //包围类的静态成员变量 //https://blog.csdn.net/chengwangbaiko/article/details/73477551 https://www.cnblogs.com/newflydd/p/4948575.html
public static void main(String[] args) throws Exception {
List<Integer> list = Arrays.asList(100, 200, 300, 400, 500); list.forEach(o -> {System.out.println(o);}); //forEach函数实现内部迭代 System.out.println("1、给出一个String类型的数组,找出其中所有不重复的素数:");
distinctPrimary("2", "3", "4", "5", "6", "7", "8", "9", "2", "3", "4", "5", "6", "7", "8", "9"); System.out.println("2、给出一个String类型的数组,找出其中各个素数,并统计其出现次数:");
primaryOccurrence("2", "3", "4", "5", "6", "7", "8", "9", "2", "3", "4", "5", "6", "7", "8", "9"); System.out.println("3、给出一个String类型的数组,求其中所有不重复素数的和(预定义的reduce操作: 如sum(),max(),min()等。):");
distinctPrimarySum("2", "3", "4", "5", "6", "7", "8", "9", "2", "3", "4", "5", "6", "7", "8", "9");
distinctPrimarySum2("2", "3", "4", "5", "6", "7", "8", "9", "2", "3", "4", "5", "6", "7", "8", "9"); System.out.println("4、生成器函数(Generator function):");
Stream.generate(Math::random).limit(5).forEach(System.out::println); System.out.println("5、//3.1、λ表达式的更多用法:");
// 嵌套的λ表达式
Callable<Runnable> c1 = () -> () -> { System.out.println("Nested lambda"); };
c1.call().run(); // 用在条件表达式中
Callable<Integer> c2 = true ? (() -> 42) : (() -> 24);
System.out.println(c2.call()); // 定义一个递归函数
// private UnaryOperator<Integer> factorial = i -> { return i == 0 ? 1 : i * factorial.apply( i - 1 ); };
// //...
// System.out.println(factorial.apply(3));
System.out.println("6、方法引用(Method reference):");
/*
Integer::parseInt //静态方法引用
System.out::print //实例方法引用
Person::new //构造器引用 super::toString //引用某个对象的父类方法
String[]::new //引用一个数组的构造器 //c1 与 c2 是一样的(静态方法引用)
Comparator<Integer> c2 = (x, y) -> Integer.compare(x, y);
Comparator<Integer> c1 = Integer::compare;
List<UserT> persons = new ArrayList<>();
//下面两句是一样的(实例方法引用1)
persons.forEach(e -> System.out.println(e));
persons.forEach(System.out::println); //下面两句是一样的(实例方法引用2)
persons.forEach(person -> person.eat());
persons.forEach(Person::eat); //下面两句是一样的(构造器引用)
strList.stream().map(s -> new Integer(s));
strList.stream().map(Integer::new); */ } //5、捕获(Capture)
/*
public void testCapture() {
int tmp3 = 3; //没有声明为final,但是effectively final的本地变量
final int tmp4 = 4; //声明为final的本地变量
int tmp5 = 5; //普通本地变量 Function<Integer, Integer> f1 = i -> i + tmp1;
Function<Integer, Integer> f2 = i -> i + tmp2;
Function<Integer, Integer> f3 = i -> i + tmp3;
Function<Integer, Integer> f4 = i -> i + tmp4;
Function<Integer, Integer> f5 = i -> {
tmp5 += i; // 编译错!对tmp5赋值导致它不是effectively final的
return tmp5;
};
//...
tmp5 = 9; // 编译错!对tmp5赋值导致它不是effectively final的
} */ //1、给出一个String类型的数组,找出其中所有不重复的素数
/**
* 你可能会觉得在这个例子里,List list被迭代了好多次,
* map,filter,distinct都分别是一次循环,效率会不好。
* 实际并非如此。这些返回另一个Stream的方法都是“lazy”的,而最后返回最终结果的collect方法则是“eager”的。
* 在遇到eager方法之前,lazy的方法不会执行。
*
* 当遇到eager方法时,前面的lazy方法才会被依次执行。
* 而且是管道贯通式执行。这意味着每一个元素依次通过这些管道。
* 例如有个元素“3”,首先它被map成整数型3;
* 然后通过filter,发现是素数,被保留下来;又通过distinct,
* 如果已经有一个3了,那么就直接丢弃,如果还没有则保留。这样,3个操作其实只经过了一次循环。
*
* 除collect外其它的eager操作还有forEach,toArray,reduce等
*/
public static void distinctPrimary(String... numbers) {
List<String> l = Arrays.asList(numbers);
List<Integer> r = l.stream()
.map(e -> new Integer(e))
// .map(e -> Integer.parseInt(e)) // 将集合流中的元素一一映射为一个新的元素,并生成到新的输出流中
.filter(e -> isPrime(e)) // 过滤,lambda表达式 .filter(e -> Primes.isPrime(e))
.distinct() // stream的高级方法,去除重复
.collect(Collectors.toList()); // 将整理好的输出流收集到新的listInt集合中
System.out.println("distinctPrimary result is: " + r);
} //2、给出一个String类型的数组,找出其中各个素数,并统计其出现次数
public static void primaryOccurrence(String... numbers) {
List<String> l = Arrays.asList(numbers);
Map<Integer, Integer> r = l.stream()
.map(e -> new Integer(e))
// .filter(e -> Primes.isPrime(e))
.filter(e -> isPrime(e))
.collect( Collectors.groupingBy(p->p, Collectors.summingInt(p->1)) ); //把结果收集到一个Map中,用统计到的各个素数自身作为键,其出现次数作为值。
System.out.println("primaryOccurrence result is: " + r);
} //3、给出一个String类型的数组,求其中所有不重复素数的和(预定义的reduce操作: 如sum(),max(),min()等。)
public static void distinctPrimarySum(String... numbers) {
List<String> l = Arrays.asList(numbers);
int sum = l.stream()
.map(e -> new Integer(e))
// .filter(e -> Primes.isPrime(e))
.filter(e -> isPrime(e))
.distinct()
.reduce(0, (x,y) -> x+y); // equivalent to .sum() reduce方法用来产生单一的一个最终结果。
System.out.println("distinctPrimarySum result is: " + sum);
}
public static void distinctPrimarySum2(String... numbers) {
List<String> l = Arrays.asList(numbers);
int sum = l.stream().map(Integer::new)
// .filter(Primes::isPrime)
.filter(e -> isPrime(e))
.distinct()
.mapToInt(item -> item)
.sum()
;
System.out.println("distinctPrimarySum2 result is: " + sum);
} //3.1、统计年龄在25-35岁的男女人数、比例 (预定义的reduce操作)
public void boysAndGirls(List<UserT> persons) {
Map<Integer, Integer> result = persons.parallelStream().filter(p -> p.getAge()>=25 && p.getAge()<=35).
collect(
Collectors.groupingBy(p->p.getSex(), Collectors.summingInt(p->1))
);
System.out.print("boysAndGirls result is " + result);
System.out.println(", ratio (male : female) is " + (float)result.get(UserT.Sex.MALE)/result.get(UserT.Sex.FEMAILE));
} static class UserT { public enum Sex {
MALE("男"),
FEMAILE("女"); private String description; Sex(String description) {
this.description = description;
} public String getDescription() {
return description;
} public void setDescription(String description) {
this.description = description;
} public static Sex fromName(String name) {
for (Sex model : Sex.values()) {
if (StringUtils.equals(model.name(), name)) {
return model;
}
}
return null;
}
} String name;
Integer age;
Integer sex; public Integer getSex() {
return sex;
} public void setSex(Integer sex) {
this.sex = sex;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} public UserT(String zm) {
this.name=zm;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
}
}
★、根据条件生成新的 array:
public static void main(String[] args){
String[] ids={"11","12","13"};
String[] contents={"a"};
String[] z1 = new String[0];
if(ids.length != contents.length){
int diff = ids.length - contents.length;
int z0 = diff + contents.length;
z1 = new String[z0];
for (int i = 0; i < contents.length; i++) {
z1[i] = contents[i];
}
}
String[] z3 = Arrays.stream(z1).map(i -> {
return i == null ? "" : i;
}).toArray(String[]::new);
Arrays.stream(z3).forEach(System.out::println);
}
java8 array、list操作 汇【4】)- Java8 Lambda表达式 函数式编程的更多相关文章
- Java8新特性 1——利用流和Lambda表达式操作集合
Java8中可以用简洁的代码来操作集合,比如List,Map,他们的实现ArrayList.以此来实现Java8的充分利用CPU的目标. 流和Lambda表达式都是Java8中的新特性.流可以实现对集 ...
- Java8初体验(1):lambda表达式语法
原文出处: 一冰_天锦 本文主要记录自己学习Java8的历程,方便大家一起探讨和自己的备忘.因为本人也是刚刚开始学习Java8,所以文中肯定有错误和理解偏差的地方,希望大家帮忙指出,我会持续修改和优化 ...
- Java8新特性(一)之Lambda表达式
.personSunflowerP { background: rgba(51, 153, 0, 0.66); border-bottom: 1px solid rgba(0, 102, 0, 1); ...
- Java8 Collections.sort()及Arrays.sort()中Lambda表达式及增强版Comparator的使用
摘要:本文主要介绍Java8 中Arrays.sort()及Collections.sort()中Lambda表达式及增强版Comparator的使用. 不废话直接上代码 import com.goo ...
- Java8新特性:Function接口和Lambda表达式参考
Lambda基本:https://blog.csdn.net/wargon/article/details/80656575 https://www.cnblogs.com/hyyq/p/742566 ...
- Util应用程序框架公共操作类(十二):Lambda表达式公共操作类(三)
今天在开发一个简单查询时,发现我的Lambda操作类的GetValue方法无法正确获取枚举类型值,以至查询结果错误. 我增加了几个单元测试来捕获错误,代码如下. /// <summary> ...
- Jquery实现对Array数组实现类似Linq的Lambda表达式的Where方法筛选
平时使用Linq,习惯了Lambda表达式,用着非常顺手,奈何在Jquery里面不能这样用,只能循环一个个判断.趁空闲时间找了找,自己写了这样的扩展方法.目前写出了三种方案,没有比较性能,觉得都可以用 ...
- 从lambda到函数式编程
Object.send(:remove_const,'TRUE') Object.send(:remove_const,'FALSE') def to_integer(pro) pro[-> n ...
- java8 array、list操作 汇【2】)- (Function,Consumer,Predicate,Supplier)应用
static class UserT { String name; public UserT(String zm) { this.name=zm; } public String getName() ...
随机推荐
- [Java学习] Java异常处理基础
Java异常是一个描述在代码段中发生的异常(也就是出错)情况的对象.当异常情况发生,一个代表该异常的对象被创建并且在导致该错误的方法中被抛出(throw).该方法可以选择自己处理异常或传递该异常.两种 ...
- LeetCode--172--阶乘后的0
问题描述: 给定一个整数 n,返回 n! 结果尾数中零的数量. 示例 1: 输入: 3 输出: 0 解释: 3! = 6, 尾数中没有零. 示例 2: 输入: 5 输出: 1 解释: 5! = 120 ...
- (GoRails) 自动侦测用户的时区,使用javascript 的jszt库。
传统方法见:http://www.cnblogs.com/chentianwei/p/9369904.html ⚠️: 两个方法最后都要有controller中的类似before_action :se ...
- codeforces 1042d//Petya and Array// Codeforces Round #510 (Div. 2)
题意:给出一个数组,求其中和小于t的区间数. 先计算前缀和数组sum[i].对当前的sum[i],查询树状数组中有几个比(sum[i]-t)大的数,那么用sum[i]减它就是一个合法区间.再将当前的s ...
- Almost Acyclic Graph CodeForces - 915D (思维,图论)
大意: 给定无向图, 求是否能删除一条边后使图无环 直接枚举边判环复杂度过大, 实际上删除一条边可以看做将该边从一个顶点上拿开, 直接枚举顶点即可 复杂度$O(n(n+m))$ #include &l ...
- 『PyTorch』第十一弹_torch.optim优化器
一.简化前馈网络LeNet import torch as t class LeNet(t.nn.Module): def __init__(self): super(LeNet, self).__i ...
- 在python中是没有NULL的,取而代之的是None,它的含义是为空
在python中是没有NULL的,取而代之的是None,它的含义是为空
- write file to stroage trigger kernel warning
when you write large files to extern stroage, the kernel may have as follow context: [ 4560.236385] ...
- mysql监控利器mysqlmtop部署安装
MySQLMTOP是一个由Python+PHP开发的MySQL企业级监控系统.系统由Python实现多进程数据采集和告警,PHP实现WEB展示和管理.最重要是MySQL服务器无需安装任何Agent,只 ...
- Android开发——1轻松战胜开发环境
写在前头的话:鄙人乃2016年本科毕业的程序yuan一枚,大学阶段从未学过安卓,java也是一知半解,回想这一年半的开发生涯真的是相当悲壮.你要是问我喜欢开发吗,当然确定一定以及肯定地告诉你不喜欢啊! ...