精华内容
下载资源
问答
  • 1. java.util.concurrent - Java 并发工具包 2. 阻塞队列 BlockingQueue 3. 数组阻塞队列 ArrayBlockingQueue 4. 延迟队列 DelayQueue 5. 链阻塞队列 LinkedBlockingQueue 6. 具有优先级的阻塞队列 ...
  • at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at org.gradle.internal....

    Terminal下输入命令

    使用以下命令中的其中一个即可
    1.
    gradlew compileDebug --stacktrace
    2.
    gradlew compileDebug --stacktrace -info
    3.
    gradlew compileDebug --stacktrace -debug 
    4.(推荐)
    gradlew compileDebugSources --stacktrace -info
    

    在这里插入图片描述

    Caused by: java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2Exception: AAPT2 error: check logs for details
            at com.google.common.util.concurrent.AbstractFuture.getDoneValue(AbstractFuture.java:503)
            at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:482)
            at com.google.common.util.concurrent.AbstractFuture$TrustedFuture.get(AbstractFuture.java:79)
            at com.android.ide.common.res2.MergedResourceWriter.end(MergedResourceWriter.java:327)
            ... 44 more
    Caused by: java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2Exception: AAPT2 error: check logs for details
            at com.google.common.util.concurrent.AbstractFuture.getDoneValue(AbstractFuture.java:503)
            at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:462)
            at com.google.common.util.concurrent.AbstractFuture$TrustedFuture.get(AbstractFuture.java:79)
            at com.android.builder.internal.aapt.v2.QueueableAapt2.lambda$compile$0(QueueableAapt2.java:136)
    Caused by: com.android.builder.internal.aapt.v2.Aapt2Exception: AAPT2 error: check logs for details
            at com.android.builder.png.AaptProcess$NotifierProcessOutput.handleOutput(AaptProcess.java:443)
            at com.android.builder.png.AaptProcess$NotifierProcessOutput.err(AaptProcess.java:395)
            at com.android.builder.png.AaptProcess$ProcessOutputFacade.err(AaptProcess.java:312)
            at com.android.utils.GrabProcessOutput$1.run(GrabProcessOutput.java:104)
    
    

    https://blog.csdn.net/u010775335/article/details/80284468

    在这里插入图片描述
    点击1位置可以查看详细信息,或者点击2位置,在Terminal命令窗口中输入 gradlew --scan(提示的命令)

    com.android.build.gradle.tasks.ResourceException: Error: java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2Exception: AAPT2 error: check logs for details
    	at com.android.build.gradle.tasks.MergeResources.doFullTaskAction(MergeResources.java:296)
    	at com.android.build.gradle.internal.tasks.IncrementalTask.taskAction(IncrementalTask.java:106)
    	at sun.reflect.GeneratedMethodAccessor231.invoke(Unknown Source)
    	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    	at java.lang.reflect.Method.invoke(Method.java:498)
    	at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
    	at org.gradle.api.internal.project.taskfactory.IncrementalTaskAction.doExecute(IncrementalTaskAction.java:46)
    	at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:39)
    	at org.gradle.api.internal.project.taskfactory.StandardTaskAction.execute(StandardTaskAction.java:26)
    	at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:121)
    	at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    	at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    	at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    	at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    	at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:110)
    	at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
    	at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
    	at org.gradle.api.internal.tasks.execution.OutputDirectoryCreatingTaskExecuter.execute(OutputDirectoryCreatingTaskExecuter.java:51)
    	at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
    	at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
    	at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:60)
    	at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:97)
    	at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:87)
    	at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
    	at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    	at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
    	at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    	at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
    	at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
    	at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
    	at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
    	at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    	at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:110)
    	at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
    	at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
    	at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:123)
    	at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:79)
    	at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:104)
    	at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:98)
    	at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:626)
    	at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:581)
    	at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:98)
    	at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
    	at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    	at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
    	at java.lang.Thread.run(Thread.java:748)
    Caused by: Error: java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2Exception: AAPT2 error: check logs for details
    	at com.android.ide.common.res2.MergedResourceWriter.end(MergedResourceWriter.java:332)
    	at com.android.ide.common.res2.DataMerger.mergeData(DataMerger.java:301)
    	at com.android.ide.common.res2.ResourceMerger.mergeData(ResourceMerger.java:412)
    	at com.android.build.gradle.tasks.MergeResources.doFullTaskAction(MergeResources.java:285)
    	... 47 more
    	Suppressed: java.lang.RuntimeException: Some file processing failed, see logs for details
    		at com.android.builder.internal.aapt.QueuedResourceProcessor.waitForAll(QueuedResourceProcessor.java:121)
    		at com.android.builder.internal.aapt.QueuedResourceProcessor.end(QueuedResourceProcessor.java:141)
    		at com.android.builder.internal.aapt.v2.QueueableAapt2.close(QueueableAapt2.java:104)
    		at com.android.build.gradle.tasks.MergeResources.doFullTaskAction(MergeResources.java:293)
    		... 47 more
    Caused by: java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2Exception: AAPT2 error: check logs for details
    	at com.google.common.util.concurrent.AbstractFuture.getDoneValue(AbstractFuture.java:503)
    	at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:462)
    	at com.google.common.util.concurrent.AbstractFuture$TrustedFuture.get(AbstractFuture.java:79)
    	at com.android.ide.common.res2.MergedResourceWriter.end(MergedResourceWriter.java:327)
    	... 50 more
    Caused by: java.util.concurrent.ExecutionException: com.android.builder.internal.aapt.v2.Aapt2Exception: AAPT2 error: check logs for details
    	at com.google.common.util.concurrent.AbstractFuture.getDoneValue(AbstractFuture.java:503)
    	at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:462)
    	at com.google.common.util.concurrent.AbstractFuture$TrustedFuture.get(AbstractFuture.java:79)
    	at com.android.builder.internal.aapt.v2.QueueableAapt2.lambda$compile$0(QueueableAapt2.java:136)
    	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    	... 1 more
    Caused by: com.android.builder.internal.aapt.v2.Aapt2Exception: AAPT2 error: check logs for details
    	at com.android.builder.png.AaptProcess$NotifierProcessOutput.handleOutput(AaptProcess.java:443)
    	at com.android.builder.png.AaptProcess$NotifierProcessOutput.err(AaptProcess.java:395)
    	at com.android.builder.png.AaptProcess$ProcessOutputFacade.err(AaptProcess.java:312)
    	at com.android.utils.GrabProcessOutput$1.run(GrabProcessOutput.java:104)
    
    
    

    参考
    https://blog.csdn.net/u010775335/article/details/80284468

    展开全文
  • import java.util.List; import java.util.Map; @Controller @RequestMapping("/user") public class UserController { @Autowired private JdbcTemplate jdbcTemplate; @RequestMapping("findAll") public String ...
    package com.example.Controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import java.util.List;
    import java.util.Map;
    
    @Controller
    @RequestMapping("/user")
    public class UserController {
        @Autowired
        private JdbcTemplate jdbcTemplate;
    
        @RequestMapping("findAll")
        public String findAll(){
            List<Map<String,Object>> list=jdbcTemplate.queryForList("select * from t_user");
            return list;
        }
    }
    

    图中的代码是我要访问数据库的时候,写的一段代码,但是却报错了
    在这里插入图片描述
    然后,我根据报错找到了答案,是因为我方法名写的是String,因此,也要和内容修改的一样,也就是改成这样:

    package com.itany.controller;
    
    import org.springframework.beans.factory.annotation.Autowired;
    
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import java.util.List;
    import java.util.Map;
    
    @Controller
    @RequestMapping("/user")
    public class UserController {
        @Autowired
        private JdbcTemplate jdbcTemplate;
    
        @RequestMapping("/findAll")
        public List<Map<String, Object>> findAll(){
            List<Map<String,Object>> list=jdbcTemplate.queryForList("select * from t_user");
            return list;
        }
    }
    
    展开全文
  • java.util.concurrent.RejectedExecutionException异常报错。 具体看了下代码,里面的执行逻辑也不难,没有外部依赖都是内存多线程cpu类型计算的逻辑。 下面是报错的线程池状态变化,由上到下,按照时间增长,最后...

    场景

    业务一切正常,突然收到一堆告警,发现全是
    java.util.concurrent.RejectedExecutionException异常报错。
    具体看了下代码,里面的执行逻辑也不难,没有外部依赖都是内存多线程cpu类型计算的逻辑。
    下面是报错的线程池状态变化,由上到下,按照时间增长,最后达到饱和。

    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 99, active threads = 75, queued tasks = 5000, completed tasks = 1595259]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 101, active threads = 74, queued tasks = 4999, completed tasks = 1595298]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 90, active threads = 70, queued tasks = 4998, completed tasks = 1595354]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 93, active threads = 75, queued tasks = 5000, completed tasks = 1595378]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 85, active threads = 72, queued tasks = 5000, completed tasks = 1595443]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 83, active threads = 70, queued tasks = 5000, completed tasks = 1595447]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 90, active threads = 81, queued tasks = 5000, completed tasks = 1595476]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 85, active threads = 74, queued tasks = 4994, completed tasks = 1595574]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 91, active threads = 80, queued tasks = 4999, completed tasks = 1595678]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 95, active threads = 85, queued tasks = 5000, completed tasks = 1595696]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 95, active threads = 87, queued tasks = 5000, completed tasks = 1595721]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 93, active threads = 85, queued tasks = 4999, completed tasks = 1595727]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 94, active threads = 85, queued tasks = 4998, completed tasks = 1595737]
    ...
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 109, active threads = 96, queued tasks = 4999, completed tasks = 1596150]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 113, active threads = 102, queued tasks = 4998, completed tasks = 1596191]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 120, active threads = 109, queued tasks = 5000, completed tasks = 1596355]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 120, active threads = 110, queued tasks = 5000, completed tasks = 1596517]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 119, active threads = 110, queued tasks = 4999, completed tasks = 1596519]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 113, active threads = 105, queued tasks = 5000, completed tasks = 1596553]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 122, active threads = 109, queued tasks = 4999, completed tasks = 1596602]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 120, active threads = 120, queued tasks = 5000, completed tasks = 1597061]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 120, active threads = 120, queued tasks = 5000, completed tasks = 1597061]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 120, active threads = 120, queued tasks = 5000, completed tasks = 1597061]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 120, active threads = 120, queued tasks = 5000, completed tasks = 1597061]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 120, active threads = 120, queued tasks = 5000, completed tasks = 1597061]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 120, active threads = 120, queued tasks = 5000, completed tasks = 1597061]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 120, active threads = 120, queued tasks = 5000, completed tasks = 1597061]
    java.util.concurrent.ThreadPoolExecutor@57b5ea0f[Running, pool size = 120, active threads = 120, queued tasks = 5000, completed tasks = 1597061]
    

    因为cpu4核,所以coresize = 40,maxsize = 120,都正常。

        private static BlockingQueue<Runnable> executorQueue = new LinkedBlockingQueue<>(5000);
        private static ExecutorService executorService = new ThreadPoolExecutor(
                Runtime.getRuntime().availableProcessors() * 10,
                Runtime.getRuntime().availableProcessors() * 30,
                60, TimeUnit.SECONDS, executorQueue);
    

    通过对ThreadPoolExecutor类分析,引发java.util.concurrent.RejectedExecutionException主要有两种原因:

    1. 线程池显示的调用了shutdown()之后,再向线程池提交任务的时候,如果你配置的拒绝策略是ThreadPoolExecutor.AbortPolicy的话,这个异常就被会抛出来。
    2. 当你的排队策略为有界队列,并且配置的拒绝策略是ThreadPoolExecutor.AbortPolicy,当线程池的线程数量已经达到了maximumPoolSize的时候,你再向它提交任务,就会抛出ThreadPoolExecutor.AbortPolicy异常。

    排查

    因为全机房、只有一个节点报错,而其他机器都正常,在这个一定保证正确的前提下。
    1、看了线上的请求量、并没有突增,所以排除外部因素
    2、看了代码逻辑,逻辑内部并没有打印报错日志,说明不是线程执行耗时导致后面的其他线程排队
    3、排除线程池是否提前关闭。并没有,因为手动没有显示关闭,另外看日志也知道里面的线程数还在变化,所以不存在关闭的说法。

    考虑是否是机器本身的原因,后面经过排查,看到那个点线上的cpu使用率突然升高、系统负载突然飙升,网卡流出、流入报文数目、tcp连接数也突然为0。具体干了什么,已经让运营去看了。至少说明我们代码没有问题。

    如下图,可以感受下:
    在这里插入图片描述

    解决

    线上第一时间出现这个问题,没想2秒,看了下报错代码逻辑,然后重启了这个节点实例(当时重启完后,观察又没问题了,带着疑惑然后才去排查)

    展开全文
  • Java 8 新特性|java.util.stream.Collectors

    千次阅读 2020-06-02 22:57:55
    Java 8 流的新类 java.util.stream.Collectors 实现了 java.util.stream.Collector 接口,同时又提供了大量的方法对流 ( stream ) 的元素执行 map and reduce 操作,或者统计操作。 1、 Collectors.averagingDouble...

    Java 8 流的新类 java.util.stream.Collectors 实现了 java.util.stream.Collector 接口,同时又提供了大量的方法对流 ( stream ) 的元素执行 map and reduce 操作,或者统计操作。

    1、 Collectors.averagingDouble()

    Collectors.averagingDouble() 方法将流中的所有元素视为 double 类型并计算他们的平均值。该方法返回的是同一个 Collectors 实例,因此可以进行链式操作。

    Collectors.averagingDouble() 接受一个参数,这个参数是一个 lambda 表达式,用于对所有的元素执行一个 map 操作。

    Java 所有集合的 stream().collect() 可以接受一个收集器实例作为其参数并返回该收集器的计算结果

    参考下面的代码,collect() 方法会把所有的元素收集起来然后传递给 Collectors.averagingDouble(d->d*2) 收集器,对每个元素执行 *2 操作后计算平均值

    package com.sjh.test.java8.collectors;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class AveragingDoubleTest {
    
        public static void main(String[] args) {
            List<Integer> list = Arrays.asList(1,2,3,4);
            Double result = list.stream().collect(Collectors.averagingDouble(d->d*2));
            System.out.println(result);
        }
    }
    

    运行结果:

    /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/...com.sjh.test.java8.collectors.AveragingDoubleTest
    5.0
    
    Process finished with exit code 0
    

    2、 Collectors.averagingInt()

    该方法和Collectors.averagingDouble()一样,不同的是它把流中的所有元素看成是 int 类型,并返回一个浮点类型的平均值

    package com.sjh.test.java8.collectors;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class AveragingIntTest {
    
        public static void main(String[] args) {
            List<Integer> list = Arrays.asList(1,2,3,4);
            Double result = list.stream().collect(Collectors.averagingInt(v->v*2));
            System.out.println(result);
        }
    }
    

    运行结果:

    /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/...com.sjh.test.java8.collectors.AveragingIntTest
    5.0
    
    Process finished with exit code 0
    

    3、 Collectors.averagingLong()

    该方法也和Collectors.averagingDouble()类似,不同的是它把流中的所有元素看成是 long 类型,并返回一个 double 类型的平均值

    package com.sjh.test.java8.collectors;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class AveragingLongTest {
    
        public static void main(String[] args) {
            List<Integer> list = Arrays.asList(1,2,3,4);
            Double result = list.stream().collect(Collectors.averagingLong(v->v*2));
            System.out.println(result);
        }
    }
    

    运行结果:

    /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/...com.sjh.test.java8.collectors.AveragingLongTest
    5.0
    
    Process finished with exit code 0
    

    4、 Collectors.averagingDouble()

    Collectors.collectingAndThen()函数应该最像 map and reduce 了,它可接受两个参数,第一个参数用于 reduce 操作,而第二参数用于 map 操作。

    也就是,先把流中的所有元素传递给第二个参数,然后把生成的集合传递给第一个参数来处理。

    例如下面的代码,先把 [1,2,3,4] 这个集合传递给 s-> ss lambda 表达式,计算得出结果为 [1,4,9,16] ,然后再把 [1,4,9,16] 传递给 v->v2 表达式,计算得出 [2,8,18,32] ,然后传递给 Collectors.averagingLong() 计算得到结果为 25.0

    package com.sjh.test.java8.collectors;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class CollectingAndThenTest {
    
        public static void main(String[] args) {
            List<Integer> list = Arrays.asList(1,2,3,4);
            Double result = list.stream().collect(Collectors.collectingAndThen(Collectors.averagingLong(v->v*2),
                    s-> s*s));
            System.out.println(result);
        }
    }
    

    运行结果:

    /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/...com.sjh.test.java8.collectors.CollectingAndThenTest
    25.0
    
    Process finished with exit code 0
    

    5、 Collectors.counting()

    Collectors.counting() 用于统计流中元素的个数。

    package com.sjh.test.java8.collectors;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class CountingTest {
    
        public static void main(String[] args) {
            List<Integer> list = Arrays.asList(1,2,3,4);
            long result= list.stream().collect(Collectors.counting());
            System.out.println(result);
        }
    }
    

    运行结果:

    /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/...com.sjh.test.java8.collectors.CountingTest
    4
    
    Process finished with exit code 0
    

    6、 Collectors.joining()

    Collectors.joining() 方法用某个指定的拼接字符串把所有元素拼接成一个字符串,并添加可选的前缀和后缀

    package com.sjh.test.java8.collectors;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class JoiningTest {
    
        public static void main(String[] args) {
            List<String> list = Arrays.asList("A","B","C","D");
            String result= list.stream().collect(Collectors.joining(",","(",")"));
            System.out.println(result);
        }
    }
    

    运行结果:

    /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/...com.sjh.test.java8.collectors.JoiningTest
    (A,B,C,D)
    
    Process finished with exit code 0
    

    7、 Collectors.maxBy() 和 Collectors.minBy()

    Collectors.maxBy()和Collectors.minBy() 两个方法分别用于计算流中所有元素的最大值和最小值。

    两个方法都可以接受一个比较器作为参数,用于如何计算最大值或最小值

    package com.sjh.test.java8.collectors;
    
    import java.util.Arrays;
    import java.util.Comparator;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class MaxByMinByTest {
    
        public static void main(String[] args) {
            List<Integer> list = Arrays.asList(30,10,20,35);
            //Get Max
            list.stream().collect(Collectors.maxBy(new MaxByMinByTest().new IntegerComp()))
                    .ifPresent(i->System.out.println(i));
            //Get Min
            list.stream().collect(Collectors.minBy(new MaxByMinByTest().new IntegerComp()))
                    .ifPresent(i->System.out.println(i));
        }
        class IntegerComp implements Comparator<Integer> {
            @Override
            public int compare(Integer i1, Integer i2) {
                if(i1 >=i2 ){
                    return 1;
                }else{
                    return -1;
                }
            }
        }
    }
    

    运行结果:

    /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/...com.sjh.test.java8.collectors.MaxByMinByTest
    35
    10
    
    Process finished with exit code 0
    

    8、 Collectors.summingInt()

    Collectors.summingInt() 方法将流中的所有元素视为 int 类型,并计算所有元素的总和 ( sum )

    package com.sjh.test.java8.collectors;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class SummingIntTest {
    
        public static void main(String[] args) {
            List<Integer> list = Arrays.asList(30,10,20,35);
            int result = list.stream().collect(Collectors.summingInt(i->i));
            System.out.println(result);
        }
    }
    

    运行结果:

    /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/...com.sjh.test.java8.collectors.SummingIntTest
    95
    
    Process finished with exit code 0 
    

    9、 Collectors.summingLong()

    Collectors.summingLong() 将流中的所有元素视为 long 类型,并计算所有元素的总和

    package com.sjh.test.java8.collectors;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class SummingLongTest {
    
        public static void main(String[] args) {
            List<Long> list = new ArrayList<>();
            list.add((long)340);
            list.add((long)240);
            list.add((long)360);
            long result = list.stream().collect(Collectors.summingLong(l->l));
            System.out.println(result);
        }
    }
    

    运行结果:

    /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/...com.sjh.test.java8.collectors.SummingLongTest
    940
    
    Process finished with exit code 0
    

    10、 Collectors.summingDouble()

    Collectors.summingDouble() 将流中的所有元素视为 double 类型,并计算所有元素的总和

    package com.sjh.test.java8.collectors;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public class SummingDoubleTest {
    
        public static void main(String[] args) {
            List<Double> list = Arrays.asList(340.5,234.56,672.76);
            Double result = list.stream().collect(Collectors.summingDouble(d->d));
            System.out.println(result);
        }
    }
    

    运行结果:

    /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/...com.sjh.test.java8.collectors.SummingDoubleTest
    1247.82
    
    Process finished with exit code 0
    

    summingInt()、summingLong()、summingDouble()这三个函数的结果的类型,就是它们如何看待元素的类型。

    11、 Collectors.toList()

    Collectors.toList() 将流中的所有元素导出到一个列表 ( List ) 中

    package com.sjh.test.java8.collectors;
    
    import java.util.List;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class ToListTest {
    
        public static void main(String[] args) {
            List<String> list = Stream.of("AA","BB","CC").collect(Collectors.toList());
            list.forEach(s->System.out.println(s));
        }
    }
    

    运行结果:

    /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/...com.sjh.test.java8.collectors.ToListTest
    AA
    BB
    CC
    
    Process finished with exit code 0
    

    12、 Collectors.toSet()

    Collectors.toSet() 把流中的所有元素导出到一个集合 ( Set ) 中,并排除重复的元素 ( Set 的特性 )

    package com.sjh.test.java8.collectors;
    
    import java.util.Set;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class ToSetTest {
    
        public static void main(String[] args) {
            Set<String> set = Stream.of("AA","AA","BB").collect(Collectors.toSet());
            set.forEach(s->System.out.println(s));
        }
    }
    

    运行结果:

    /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/...com.sjh.test.java8.collectors.ToSetTest
    AA
    BB
    
    Process finished with exit code 0
    

    13、 Collectors.toMap()

    Collectors.toMap() 将流中的所有元素导出到一个哈希表 ( Map ) 中。该方法接受两个参数,第一个参数用于生成键 ( key ) ,第二个参数用于生成值 ( value )。两个参数都是 Lambda 表达式。

    package com.sjh.test.java8.collectors;
    
    import java.util.Map;
    import java.util.stream.Collectors;
    import java.util.stream.Stream;
    
    public class ToMapTest {
    
        public static void main(String[] args) {
            Map<String,String> map = Stream.of("AA","BB","CC").collect(Collectors.toMap(k->k, v->v+v));
            map.forEach((k,v)->System.out.println("key:"+k +" value:"+v));
        }
    }
    

    运行结果:

    /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/...com.sjh.test.java8.collectors.ToMapTest
    key:CC value:CCCC
    key:BB value:BBBB
    key:AA value:AAAA
    
    Process finished with exit code 0
    

    14、 Collectors.mapping()

    Collectors.mapping() 一般用于多重 map and reduce 中。Java 文档中描述的原型如下:

    mapping(Function<? super T,? extends U> mapper, Collector<? super U,A,R> downstream)
    

    第一个参数用于 map ,第二个参数用于 reduce

    package com.sjh.test.java8.collectors;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    
    public class MappingTest {
    
        public static void main(String[] args) {
            List<Person> list = Person.getList();
            Map<Integer, String> nameByAge
                    = list.stream().collect(Collectors.groupingBy(Person::getAge,
                    Collectors.mapping(Person::getName, Collectors.joining(","))));
            nameByAge.forEach((k,v)->System.out.println("Age:"+k +" Persons: "+v));
        }
    }
    class Person {
        private String name;
        private int age;
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public int getAge() {
            return age;
        }
        public static List<Person> getList() {
            List<Person> list = new ArrayList<>();
            list.add(new Person("JayLa", 30));
            list.add(new Person("LayMan", 20));
            list.add(new Person("Tom", 20));
            list.add(new Person("XinYi", 30));
            return list;
        }
    }
    

    运行结果:

    /Library/Java/JavaVirtualMachines/jdk1.8.0_171.jdk/...com.sjh.test.java8.collectors.MappingTest
    Age:20  Persons: LayMan,Tom
    Age:30  Persons: JayLa,XinYi
    
    Process finished with exit code 0
    

    我是二哥(Jayla),每天总结一点点,每天进步一点点。
    我是二哥(Jayla),欢迎大家关注我的公众号:
    每天总结一点点,每天进步一点点。
    专注Java相关知识,每天准时分享干货。 SpringBoot/Oracle/Git/Linux/Mysql 期待您的加入~
    在这里插入图片描述

    展开全文
  • } 代码运行起来会报如下错误: java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909) at java.util.ArrayList$Itr.next(ArrayList.java:859) ......
  • 控制台报错如下 ...nested exception is java.lang.ClassCastException:java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList 报错代码 //获取一个字符串数组 String[] idsArr= s.sp.
  • 为应对近期单位认证:整理点Java知识 首先整理Java常见的类库: 1.Java.lang 这个算是我们开发经常用到的基础类了,包含的类有object超类,8种类型的包装类,字符串类,线程类,异常类等 如下所示:图来自:链接 ...
  • 先贴出异常 服务器的CPU使用率一直保持在10%左右,...是java进程跑死的,只能找java进程下哪些线程高cpu使用率 问题线程已经找到 USER %CPU PRI SCNT WCHAN USER SYSTEM TID TIME [root@27a2a017-029b-48d8-...
  • Caused by: java.lang.ClassCastException: java.util.HashMap$Node cannot be cast to java.util.HashMap$TreeNode at java.util.HashMap$TreeNode.moveRootToFront(HashMap.java:1835) at java.util.HashMap$...
  • I want to convert java.time.LocalDate into java.util.Date type. 我想将java.time.LocalDate转换为java.util.
  • Process: com.xxx.yyy Flags: 0xc8be45 Package: com.xxx.yyy v1000 (xxxxxxx-yyyyyyyy...Build: zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz:eng/test-keys java.lang.NullPointerException: A...
  • at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) at java.lang.Thread.run...
  • nested exception is java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList</p><p><b>Description</b> The server encountered an unexpected condition that ...
  • ### Cause: java.lang.IllegalArgumentException: invalid comparison: java.util.Date and java.lang.String, dubbo version: 2.6.0.2, current host: 10.18.32.208 org.mybatis.spring.MyBatisSystemException: ...
  • 最近遇到了一个问题: ERROR ...java.lang.ClassCastException: java.lang.Integer cannot be cast to java.util.List at com.xxl.job.core.thread.TriggerCallbackThrea...
  • ResourceBundle类是java提供的一个读取properties文件(配置文件)的一种方法。 文件中以#开头做为注释,下面是我的数据库连接的配置文件 #数据库配置信息 DRIVER=com.mysql.jdbc.Driver URL=jdbc:mysql://localhost...
  • 这个问题是我之前遇到的 public List&amp;lt;T&amp;gt; list(){ return (List&amp;lt;T&amp;gt;)map.values(); } 在别人的博客里找到了解决方案 附上链接 大佬的博客
  • java中的import java.util是什么意思

    千次阅读 2021-03-05 12:50:05
    java中的import java.util是什么意思发布时间:2020-06-17 10:00:01来源:亿速云阅读:177作者:Leahjava中的import java.util是什么意思?...“import java.util.*”语句表示什么意思?1、“import java.util....
  • nested exception is java.lang.ClassCastException: java.lang String cannot be cast to java.util.Map 首先,这个错误很明显,类型转换异常,当时后端查找了下,没问题,打断点根本就没有进入到程序中,同
  • java.lang.ClassCastException: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList 解决方法: 在以上步骤中再增加一次转换 String str = "0,0,0,0,0" String[] array = .split(","); ...
  • 1、util.Date和sql.Date之间的关系 我们来看下java.sql.Date的源码 package java.sql; import java.time.Instant;...public class Date extends java.util.Date {} 从以上源码可以看出,sql.Date是util.Date...
  • 问题描述: Caused by: java.util.NoSuchElementException 问题分析: 1、sql语句中缺失一个(符号。
  • java.lang.NullPointerException at java.util.Properties$LineReader.readLine(Properties.java:434) at java.util.Properties.load0(Properties.java:353) at java.util.Properties.load(Properties....
  • 在创建 Date 对象的时候,总会有两个选择 java.util.Date、java.sql.Date,我们直观的认为在操作数据库时间字段时,我们使用 java.sql.Date 创建 Date 对象,其他情况下使用 java.util.Date 创建 Date 对象。...
  • 在 intellij idea 编辑器中,把一个Map类型的数据,强制类型转换的时候。...Unchecked cast: 'java.lang.Object' to 'java.util.List&lt;java.lang.Object&gt;' 或者Unchecked assignment:'jav...
  • "import java.util.Scanner"与"import java.util.*"的区别:

    万次阅读 多人点赞 2019-04-01 16:40:38
    "import java.util.Scanner"与"import java.util.*"的区别: 1、“importjava.util.*;”表示的是把util这个包下的全部类导入到程序中;而“importjava.util.Scanner;”表示的是只把util包下的Scanner类导入到程序...
  • nested exception is org.apache.ibatis.type.TypeException: Could not set parameters for mapping: ParameterMapping{property='createTime', mode=IN, javaType=class java.util.Date, jdbcType=null, ...
  • java.util.concurrent.ExecutionException:报错解决 报错内容 严重: A child container failed during start java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start ...
  • java.util.zip.ZipException

    千次阅读 2017-11-23 09:16:49
    这两天遇见的问题如下: 十一月 23, 2017 9:02:46 上午 org.apache.catalina.startup.ContextConfig ...严重: Unable to process Jar entry [org/ibex/nestedvm/util/Seekable$InputStream.class] from Jar

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 2,363,298
精华内容 945,319
关键字:

java.util

java 订阅
友情链接: ml.rar