我做了一些PoC来比较两种类型的实现交互列表的性能.
第一个是使用纯java,foreach并使用'if'检查每个元素.
第二种方法是这样使用lambda:
int max1 = lists1.stream()
.mapToInt(i -> i)
.max()
.getAsInt();
long finalCount = lists1.stream()
.filter(p -> p.intValue() == max1)
.count();
Run Code Online (Sandbox Code Playgroud)
显然使用lambda比使用经典java快5倍foreach.
我非常有信心强制要求lambda在我当前的项目中使用我的团队,就像规则一样,禁止使用经典java foreach.
我的问题是,如果存在一些我无法应用此规则的场景(需要lambda),我的意思是,如果存在异常,我无法使用lambda集合.
Function<Double,Integer> f1=(d)-> {
if(d>5)
return 0;
return 1;
};
DoubleToIntFunction f2=(d)-> {
if(d>5)
return 1;
return 0;
};
double d=5.0;
f1.apply(d);
f2.applyAsInt(d);
Run Code Online (Sandbox Code Playgroud)
将f1优化为DoubleToIntFunction(有些像f2).
这个问题是对类别中的分区java流的一种后续跟进
我有一个stream<A>,在哪里
class A {
String category();
String data();
}
Run Code Online (Sandbox Code Playgroud)
我想得到一个map<String, list<String>>,其中原始流基于值被分区为子列表category(),然后映射到仅提取data().使用for循环实现它是非常简单的,但是有可能获得利用java流的更优雅的解决方案吗?
例:
鉴于{[a, xyz], [a, zyx], [b, abc]},我想得到一张地图:
a -> {xyz, zyx}
b -> {abc}
Run Code Online (Sandbox Code Playgroud) 有一个类A可能以某种方式映射到另一个类B或其他类:
class A {}
class B {
final A a;
B(A a) {
this.a = a;
}
}
Run Code Online (Sandbox Code Playgroud)
还有一个映射器工厂,它A根据作为参数传递的第二个类类型将映射器从另一个类返回到另一个类:
class Mapper {
static Function<A, B> a2bmapper = B::new;
static <R> Function<A, R> findMapper(Class<R> cls) {
if(cls == B.class) {
return a2bmapper;
}
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是在这一行:
return a2bmapper;
Run Code Online (Sandbox Code Playgroud)
java编译器问题不兼容类型:必需R,找到B和IDE建议转换为Function<A,R>.这是为什么?R只是一种通用类型,应该用B.
我有以下代码.
我想根据状态代码得到不同的错误消息,如果成功它应该返回对象..如何从一个方法返回这种不同的数据类型?
public EstimateTimeResult getEstimateTime(@RequestBody EstimateTimeCall estimateTimeCall,@PathVariable("empid") Long empid) throws IOException{
String URL=baseApi+"/estimates/time";
if(estimateTimeCall.getProduct_id().isEmpty() || estimateTimeCall.getProduct_id()==null || estimateTimeCall.getProduct_id()==""){
URL+="?start_latitude="+estimateTimeCall.getStart_latitude().toString()+"&start_longitude="+estimateTimeCall.getStart_longitude().toString();
}else{
URL+="?start_latitude="+estimateTimeCall.getStart_latitude().toString()+"&start_longitude="+estimateTimeCall.getStart_longitude().toString()+"&product_id="+estimateTimeCall.getProduct_id();
}
//Header Set
HttpHeaders requestHeaders=getHeader(empid);
//Do Request
HttpEntity requestEntity=new HttpEntity(requestHeaders);
ResponseEntity<EstimateTimeResult> response=restTemplate.exchange(URL,HttpMethod.GET,requestEntity,EstimateTimeResult.class);
org.springframework.http.HttpStatus statusCode=response.getStatusCode();
if(statusCode.value()==422){
return "Required start latitude,longitude";
}
return response.getBody();
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试创建一个素数的无限IntStream,它必须很快 - 在几秒钟内产生大约一百万个素数.所以我尝试创建用过滤器调用IntStream本身生成的流:
IntStream primeStream = IntStream.iterate(2, n -> n + 1)
.filter(PrimeStream::isPrime);
Run Code Online (Sandbox Code Playgroud)
与isPrime像这样:
public boolean isPrime(int n, IntStream primeStream) {
primeStream.forEach((p) -> {
if (n % p == 0)
return false;
if (p > Math.sqrt(n))
break;
});
return true;
}
Run Code Online (Sandbox Code Playgroud)
那可能吗?或者还有其他方式使用Stream来完成我的任务吗?
我曾经有一个可调用的类
class SampleTask implements Callable<Double> {
@Override
public Double call() throws Exception {
return 0d;
}
}
Run Code Online (Sandbox Code Playgroud)
我曾经用来ExecutorService提交Callable.如何改用CompletableFuture.supplyAsync?
以下代码无法编译
SampleTask task = new SampleTask();
CompletableFuture.supplyAsync(task);
Run Code Online (Sandbox Code Playgroud)
不存在变量U类型的实例,因此SampleTask符合Supplier
我stream喜欢这样.是否有可能从.map(i->arr[i]).map(arr)改为:因为两者都是我?
public String toString() {
return Arrays.toString(IntStream.range(0, position).map(i->arr[i]).toArray());
}
Run Code Online (Sandbox Code Playgroud) 拥有一组抽象对象: Set<Foo> foes;
我想要一个像这样的方法:
List<? extends Foo> getFoesByType(TypeEnum type);
Run Code Online (Sandbox Code Playgroud)
我试过了:
List<? extends Foo> result = new ArrayList<>();
for(Foo f : foes) {
if(f.getType() == type) {
switch(type) {
case TYPE1:
f = (FooType1) f;
break;
case TYPE2:
/*...*/
}
result.add(f);
/*The method add(capture#1-of ?) in the type
List<capture#1-of ?> is not applicable for the arguments (Foo)*/
}
}
return result;
Run Code Online (Sandbox Code Playgroud)
但是我收到了一个错误.
我希望能够做到这一点:List<FooType1> foesType1 = getFooesByType(TypeEnum.TYPE1);哪种方法是正确的?
我想检查目标时间是否在两个给定时间之间,而不考虑使用Java8时间的日期.假设开始时间是"21:30",结束时间是"06:30",目标时间是"03:00",所以程序应该返回true.
@Test
public void posteNuit()
{
DateTimeFormatter format = DateTimeFormatter.ofPattern("HH:mm");
String s = "21:30";
String e = "06:30";
String t = "03:00";
LocalTime startTime = LocalTime.parse(s, format);
LocalTime endTime = LocalTime.parse(e, format);
LocalTime targetTime = LocalTime.parse(t, format);
if ( targetTime.isBefore(endTime) && targetTime.isAfter(startTime) ) {
System.out.println("Yes! night shift.");
} else {
System.out.println("Not! night shift.");
}
}
Run Code Online (Sandbox Code Playgroud) java-8 ×10
java ×9
java-stream ×3
lambda ×2
function ×1
generics ×1
java-time ×1
javacompiler ×1
recursion ×1
time ×1