首页
统计
关于
Search
1
Sealos3.0离线部署K8s集群
1,272 阅读
2
类的加载
832 阅读
3
Spring Cloud OAuth2.0
827 阅读
4
SpringBoot自动装配原理
735 阅读
5
集合不安全问题
631 阅读
笔记
Java
多线程
注解和反射
JVM
JUC
设计模式
Mybatis
Spring
SpringMVC
SpringBoot
MyBatis-Plus
Elastic Search
微服务
Dubbo
Zookeeper
SpringCloud
Nacos
Sentinel
数据库
MySQL
Oracle
PostgreSQL
Redis
MongoDB
工作流
Activiti7
Camunda
消息队列
RabbitMQ
前端
HTML5
CSS
CSS3
JavaScript
jQuery
Vue2
Vue3
Canvas
Linux
容器
Docker
Containerd
Kubernetes
Python
FastApi
OpenCV
数据分析
牛牛生活
登录
Search
标签搜索
Java
CSS
mysql
RabbitMQ
JavaScript
Redis
OpenCV
JVM
Mybatis-Plus
Camunda
多线程
CSS3
Python
Canvas
Spring Cloud
注解和反射
Activiti
工作流
SpringBoot
ndarray
蘇阿細
累计撰写
435
篇文章
累计收到
4
条评论
首页
栏目
笔记
Java
多线程
注解和反射
JVM
JUC
设计模式
Mybatis
Spring
SpringMVC
SpringBoot
MyBatis-Plus
Elastic Search
微服务
Dubbo
Zookeeper
SpringCloud
Nacos
Sentinel
数据库
MySQL
Oracle
PostgreSQL
Redis
MongoDB
工作流
Activiti7
Camunda
消息队列
RabbitMQ
前端
HTML5
CSS
CSS3
JavaScript
jQuery
Vue2
Vue3
Canvas
Linux
容器
Docker
Containerd
Kubernetes
Python
FastApi
OpenCV
数据分析
牛牛生活
页面
统计
关于
搜索到
435
篇与
的结果
2021-02-15
四大函数式接口
四大函数式接口函数式接口只有一个方法的接口4大函数式接口:consumer,funtion,predicate,supplierFunction函数式接口package com.sw.function; import java.util.function.Function; /** * @Author suaxi * @Date 2021/2/15 22:00 * Function函数式接口 */ public class Test01 { public static void main(String[] args) { // Function<String, String> function = new Function<String, String>() { // @Override // public String apply(String s) { // return s; // } // }; //lambda表达式简化 Function<String, String> function = (s) ->{ return s; }; System.out.println(function.apply("函数式接口测试")); } } Predicate断定型接口package com.sw.function; import java.util.function.Predicate; /** * @Author suaxi * @Date 2021/2/15 22:09 * Predicate断定型接口,返回值为boolean类型 */ public class PredicateTest { public static void main(String[] args) { // Predicate<String> predicate = new Predicate<String>() { // @Override // public boolean test(String s) { // return s.isEmpty(); // } // }; Predicate<String> predicate = (str) ->{ return str.isEmpty(); }; System.out.println(predicate.test("abc")); } } Consummer消费型接口package com.sw.function; import java.util.function.Consumer; /** * @Author suaxi * @Date 2021/2/15 22:17 * Consummer消费型接口,只有输入参数,没有返回值 */ public class ConsumerTest { public static void main(String[] args) { // Consumer<String> consumer = new Consumer<String>() { // @Override // public void accept(String s) { // System.out.println(s); // } // }; Consumer<String> consumer = (str) ->{ System.out.println(str); return; }; consumer.accept("消费型接口测试"); } } Supplier供给型接口package com.sw.function; import java.util.function.Supplier; /** * @Author suaxi * @Date 2021/2/15 22:25 * Supplier 供给型接口 没有输入参数,只有返回值 */ public class SupplierTest { public static void main(String[] args) { // Supplier<String> supplier = new Supplier<String>() { // @Override // public String get() { // return "你好,谢谢"; // } // }; Supplier<String> supplier = () -> { return "你好,谢谢"; }; System.out.println(supplier.get()); } }
2021年02月15日
64 阅读
0 评论
0 点赞
2021-02-14
线程池
线程池线程池:三大方法、7大参数、4种拒绝策略池化技术事先准备好一些资源,要用的时候从池子中取,用完之后还回去优点:降低资源的消耗提高响应速度方便管理三大方法package com.sw.pool; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @Author suaxi * @Date 2021/2/14 21:23 */ public class PoolTest { public static void main(String[] args) { //ExecutorService pool = Executors.newSingleThreadExecutor(); //单个线程 //ExecutorService pool = Executors.newFixedThreadPool(10); //创建一个固定大小的线程池 ExecutorService pool = Executors.newCachedThreadPool(); //线程池大小可弹性伸缩 try { for (int i = 0; i < 50; i++) { pool.execute(() -> { System.out.println(Thread.currentThread().getName() + "--->Pool Test"); }); } } catch (Exception e) { e.printStackTrace(); } finally { //线程池用完,程序结束,关闭线程池 pool.shutdown(); } } } 七大参数 public ThreadPoolExecutor(int corePoolSize, //核心线程池大小 int maximumPoolSize, //最大线程池大小 long keepAliveTime, //超时后多长时间没人操作就关闭 TimeUnit unit, //超时单位 BlockingQueue<Runnable> workQueue, //阻塞队列 ThreadFactory threadFactory, //线程工厂,用于创建线程 RejectedExecutionHandler handler) { //拒绝策略 if (corePoolSize < 0 || maximumPoolSize <= 0 || maximumPoolSize < corePoolSize || keepAliveTime < 0) throw new IllegalArgumentException(); if (workQueue == null || threadFactory == null || handler == null) throw new NullPointerException(); this.acc = System.getSecurityManager() == null ? null : AccessController.getContext(); this.corePoolSize = corePoolSize; this.maximumPoolSize = maximumPoolSize; this.workQueue = workQueue; this.keepAliveTime = unit.toNanos(keepAliveTime); this.threadFactory = threadFactory; this.handler = handler; }图片来源:狂神说Java手动创建一个线程池package com.sw.pool; import java.util.concurrent.*; /** * @Author suaxi * @Date 2021/2/14 21:23 * 4种拒绝策略: * AbortPolicy() 线程池满了,还有人进来,不处理这个人的请求,同时抛出异常 * CallerRunsPolicy() 哪里来的请求,回到哪里去(请求对应的主方法) * DiscardPolicy() 队列满了,丢掉后来的请求,不抛出异常 * DiscardOldestPolicy() 队列满了,尝试去和最早进行服务的窗口竞争,看那里的服务是否快要结束了,结束就进去提出请求,这种策略也不抛出异常 */ public class ThreadPoolExecutorTest { public static void main(String[] args) { //自定义线程池 ExecutorService pool = new ThreadPoolExecutor( 2, 5, 3, TimeUnit.SECONDS, new LinkedBlockingDeque<>(3), Executors.defaultThreadFactory(), new ThreadPoolExecutor.DiscardOldestPolicy()); try { for (int i = 0; i < 50; i++) { pool.execute(() -> { System.out.println(Thread.currentThread().getName() + "--->Pool Test"); }); } } catch (Exception e) { e.printStackTrace(); } finally { //线程池用完,程序结束,关闭线程池 pool.shutdown(); } } } 4种拒绝策略AbortPolicy() 线程池满了,还有人进来,不处理这个人的请求,同时抛出异常CallerRunsPolicy() 哪里来的请求,回到哪里去(请求对应的主方法)DiscardPolicy() 队列满了,丢掉后来的请求,不抛出异常DiscardOldestPolicy() 队列满了,尝试去和最早进行服务的窗口竞争,看那里的服务是否快要结束了,结束就进去提出请求,这种策略也不抛出异常小结1、线程池不允许使用Executor创建(不安全),而是通过ThreadPoolExecutor这样的方式2、如何定义线程池最大的大小?(1) CPU密集型根据cpu核数来设定Runtime.getRuntime().availableProcessors();(2) IO密集型判断程序中十分耗IO的线程,一般设置为其两倍的大小
2021年02月14日
62 阅读
0 评论
0 点赞
2021-02-14
阻塞队列
阻塞队列写:如果队列满了,就必须阻塞等待取:如果队列是空的,必须阻塞等待生产阻塞队列的四组API 抛出异常不抛异常,有返回值等待阻塞等待超时添加addofferputoffer(,,)移除removepolltakepoll(,)检测队首元素elementpeek--测试Demo:package com.sw.blockingQueue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.TimeUnit; /** * @Author suaxi * @Date 2021/2/14 19:57 * 阻塞队列 */ public class BlockingQueueTest { public static void main(String[] args) throws InterruptedException { test04(); } //1.抛出异常 public static void test01(){ //队列初始大小为3 ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3); System.out.println(blockingQueue.add("A")); System.out.println(blockingQueue.add("B")); System.out.println(blockingQueue.add("C")); //java.lang.IllegalStateException: Queue full 队列已满 //System.out.println(blockingQueue.add("D")); System.out.println(blockingQueue.element()); //检测队首元素 System.out.println("-----分割线-----"); System.out.println(blockingQueue.remove()); System.out.println(blockingQueue.remove()); System.out.println(blockingQueue.remove()); //java.util.NoSuchElementException 没有目标元素 System.out.println(blockingQueue.remove()); } //2.不抛出异常,有返回值 public static void test02(){ //队列初始大小为3 ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3); System.out.println(blockingQueue.offer("A")); System.out.println(blockingQueue.offer("B")); System.out.println(blockingQueue.offer("C")); System.out.println(blockingQueue.offer("D")); //false System.out.println(blockingQueue.peek()); System.out.println("-----分割线-----"); System.out.println(blockingQueue.poll()); System.out.println(blockingQueue.poll()); System.out.println(blockingQueue.poll()); System.out.println(blockingQueue.poll()); //null } //3.等待,阻塞(一直阻塞) public static void test03() throws InterruptedException { //队列初始大小为3 ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3); blockingQueue.put("A"); blockingQueue.put("B"); blockingQueue.put("C"); //blockingQueue.put("D"); //位置不够了,会一直阻塞 System.out.println("-----分割线-----"); System.out.println(blockingQueue.take()); System.out.println(blockingQueue.take()); System.out.println(blockingQueue.take()); System.out.println(blockingQueue.take()); //没有这个元素,会一直阻塞 } //4.等待,阻塞(等待超时) public static void test04() throws InterruptedException { //队列初始大小为3 ArrayBlockingQueue<Object> blockingQueue = new ArrayBlockingQueue<>(3); System.out.println(blockingQueue.offer("A")); System.out.println(blockingQueue.offer("B")); System.out.println(blockingQueue.offer("C")); System.out.println(blockingQueue.offer("D",2, TimeUnit.SECONDS)); //等待超过2秒退出 System.out.println(blockingQueue.peek()); System.out.println("-----分割线-----"); System.out.println(blockingQueue.poll()); System.out.println(blockingQueue.poll()); System.out.println(blockingQueue.poll()); System.out.println(blockingQueue.poll(2,TimeUnit.SECONDS)); //等待超过2秒退出 } } SynchronousQueue 同步队列没有容量,put一个元素之后,必须先take取出来,才能再put进去值package com.sw.blockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.TimeUnit; /** * @Author suaxi * @Date 2021/2/14 20:58 * 同步队列 */ public class SynchronousQueueTest { public static void main(String[] args) { //没有初始容量,put之后必须进行take,才能再进行put操作 BlockingQueue<String> synchronousQueue = new SynchronousQueue<>(); //put new Thread(() -> { try { System.out.println(Thread.currentThread().getName() + "进行put01操作"); synchronousQueue.put("Hello"); System.out.println(Thread.currentThread().getName() + "进行put02操作"); synchronousQueue.put("nihao"); System.out.println(Thread.currentThread().getName() + "进行put03操作"); synchronousQueue.put("xiexie"); } catch (InterruptedException e) { e.printStackTrace(); } }, "A").start(); //take new Thread(() -> { try { TimeUnit.SECONDS.sleep(3); System.out.println(Thread.currentThread().getName() + "--->" + synchronousQueue.take()); TimeUnit.SECONDS.sleep(3); System.out.println(Thread.currentThread().getName() + "--->" + synchronousQueue.take()); TimeUnit.SECONDS.sleep(3); System.out.println(Thread.currentThread().getName() + "--->" + synchronousQueue.take()); } catch (InterruptedException e) { e.printStackTrace(); } }, "B").start(); /* 输出结果: A进行put01操作 B--->Hello A进行put02操作 B--->nihao A进行put03操作 B--->xiexie */ } }
2021年02月14日
42 阅读
0 评论
0 点赞
2021-02-14
ReadWriteLock读写锁
读写锁ReadWriteLock读写锁,一个用于只读操作,一个用于写入package com.sw.readWriteLock; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * @Author suaxi * @Date 2021/2/14 0:10 * ReadWriteLock 读写锁 * 独占锁(写) 一次只能被一个线程占有 * 共享锁(读) 可以被多个线程同时占有 * 读-读 可以共存 * 读-写 不能共存 * 写-写 不能共存 */ public class ReadWriteLockTest { public static void main(String[] args) { MyCacheLock myCache = new MyCacheLock(); for (int i = 1; i <= 5 ; i++) { final int temp = i; new Thread(() ->{ myCache.put(temp+"",temp+""); },String.valueOf(i)).start(); } for (int i = 1; i <= 5 ; i++) { final int temp = i; new Thread(() ->{ myCache.get(temp+""); },String.valueOf(i)).start(); } } } class MyCacheLock{ private volatile Map<String,Object> map = new HashMap<>(); //相比于之前的lock锁,此处对线程的控制更加细粒度 private ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); //存 写 public void put(String key,Object value){ try { readWriteLock.writeLock().lock(); System.out.println(Thread.currentThread().getName()+"写入---"+key); map.put(key, value); System.out.println(Thread.currentThread().getName()+"写入完成"); }catch (Exception e){ e.printStackTrace(); }finally { readWriteLock.writeLock().unlock(); } } //取 读 public void get(String key){ try { readWriteLock.readLock().lock(); System.out.println(Thread.currentThread().getName()+"读取---"+key); map.get(key); System.out.println(Thread.currentThread().getName()+"读取完成"); }catch (Exception e){ e.printStackTrace(); }finally { readWriteLock.readLock().unlock(); } } } class MyCache{ private volatile Map<String,Object> map = new HashMap<>(); //存 写 public void put(String key,Object value){ System.out.println(Thread.currentThread().getName()+"写入---"+key); map.put(key, value); System.out.println(Thread.currentThread().getName()+"写入完成"); } //取 读 public void get(String key){ System.out.println(Thread.currentThread().getName()+"读取---"+key); map.get(key); System.out.println(Thread.currentThread().getName()+"读取完成"); } }未使用读写锁之前,存在线程占用的问题:使用读写锁之后,执行顺序为:A写入--->A写入完成,B写入--->B写入完成,依次进行
2021年02月14日
90 阅读
0 评论
0 点赞
2021-02-12
JUC常用的辅助类
常用的辅助类1、CountDownLatch允许一个或多个线程等待其他线程完成操作package com.sw.assist; import java.util.concurrent.CountDownLatch; /** * @Author suaxi * @Date 2021/2/12 21:41 * <p> * assist 辅助类 */ //减法计数器 public class CountDownLatchTest { public static void main(String[] args) throws InterruptedException { //总数为6 CountDownLatch countDownLatch = new CountDownLatch(6); for (int i = 1; i <= 6; i++) { new Thread(() -> { System.out.println(Thread.currentThread().getName() + "--->走出教室"); countDownLatch.countDown(); //数量减1 }, String.valueOf(i)).start(); } countDownLatch.await(); //等待计数器归零,再向下执行 System.out.println("学生放学离开教室,班长锁门"); } } CountDownLatch原理:countDownLatch.countDown(); //数量减1countDownLatch.await(); //等待计数器归零,再向下执行执行方法,线程调用countDown();,使计数器数量减1,当计数器变为0时,countDownLatch.await();就会被唤醒,继续执行方法2、CyclicBarrier实现一组线程互相等待,当所有的线程都到达某个屏障点后再进行后续的操作package com.sw.assist; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; /** * @Author suaxi * @Date 2021/2/12 21:56 */ //加法计数器 public class CyclicBarrierTest { public static void main(String[] args) { //10个学生都到教室后,老师才开始上课 CyclicBarrier cyclicBarrier = new CyclicBarrier(10, () -> { System.out.println("孙老师开始上课"); }); for (int i = 1; i <= 10; i++) { //注:lambda表达式不能直接操作for循环中的i,它只是简化了new对象的过程 final int temp = i; new Thread(() -> { System.out.println(Thread.currentThread().getName() + "学生" + temp + "进入教室"); try { cyclicBarrier.await(); //等待 } catch (InterruptedException e) { e.printStackTrace(); } catch (BrokenBarrierException e) { e.printStackTrace(); } }).start(); } } } 3、Semaphore可以控制同时访问线程的个数package com.sw.assist; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; /** * @Author suaxi * @Date 2021/2/12 22:10 */ //停车位 public class SemaphoreTest { public static void main(String[] args) { //线程数量:提供3个停车位 Semaphore semaphore = new Semaphore(3); for (int i = 1; i <= 6; i++) { new Thread(() -> { try { semaphore.acquire(); //得到 System.out.println(Thread.currentThread().getName() + "---驶入停车位"); TimeUnit.SECONDS.sleep(3); System.out.println(Thread.currentThread().getName() + "---离开停车位"); } catch (InterruptedException e) { e.printStackTrace(); } finally { semaphore.release(); //释放 } }, String.valueOf(i)).start(); } } } semaphore.acquire(); //得到,如果当前提供的线程已经满了,则等待,直到线程被释放semaphore.release(); //释放,释放当前的信号量,然后唤醒等待的线程作用:多个共享资源互斥的使用;并发限流(控制最大线程数)
2021年02月12日
73 阅读
0 评论
0 点赞
2021-02-12
Callable()
Callable()可以有返回值,可以抛出异常Callable通过Runnable接口的实现类FetuerTask调用线程package com.sw.callable; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.FutureTask; /** * @Author suaxi * @Date 2021/2/12 21:24 */ public class callableTest { public static void main(String[] args) throws ExecutionException, InterruptedException { MyThread thread = new MyThread(); FutureTask futureTask = new FutureTask(thread); //适配类 new Thread(futureTask,"A").start(); new Thread(futureTask,"B").start(); /* call()方法测试 泛型的参数 = 方法的返回值 相同的两个线程运行后只返回一个结果(有缓存) */ Object o = futureTask.get(); //获取callable返回值,此处的get可能会产生阻塞,接收返回值时可能需要等待 System.out.println(o); } } class MyThread implements Callable<String>{ @Override public String call(){ System.out.println("call()方法测试"); return "泛型的参数 = 方法的返回值"; } }
2021年02月12日
95 阅读
0 评论
0 点赞
2021-02-05
Stream流的使用笔记
Stream流一、遍历/匹配 foreach/find/matchpackage com.sw.demo.stream; import java.util.Arrays; import java.util.List; import java.util.Optional; /** * 1.遍历/匹配(foreach/find/match) */ public class foreach01 { public static void main(String[] args) { List<Integer> list = Arrays.asList(1, 77, 5, 4, 33, 677, 86, 43); //遍历输出符合条件的元素 list.stream().filter(x -> x > 6).forEach(System.out::println); //匹配第一个 Optional<Integer> findFirst = list.stream().filter(x -> x > 6).findFirst(); //匹配任意一个元素(适用于并行流) Optional<Integer> findAny = list.stream().filter(x -> x > 6).findAny(); //是否包含符合指定条件的元素 boolean flag = list.stream().anyMatch(x -> x > 6); System.out.println("匹配第一个元素" + findFirst.get()); System.out.println("匹配任意一个元素" + findAny.get()); System.out.println("是否存在大于6的值" + flag); } } 二、筛选 filter按照一定的规则校验流中的元素,将符合条件的元素提取到新的流中package com.sw.demo.stream; import com.sw.demo.pojo.Person; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * 2.筛选员工中工资高于8000的人,并形成新的集合 */ public class filter02 { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 18, "male", "昆明")); personList.add(new Person("Jack", 7000, 19, "male", "楚雄")); personList.add(new Person("Lily", 7800, 20, "female", "楚雄")); personList.add(new Person("Anni", 8200, 21, "female", "大理")); personList.add(new Person("Owen", 9500, 22, "male", "昆明")); personList.add(new Person("Alisa", 7900, 22, "female", "保山")); List<String> result = personList.stream().filter(x -> x.getSalary()>8000).map(Person::getName).collect(Collectors.toList()); System.out.println("工资大于8000的员工:"+result); } } 三、聚合 max/min/count与MySQL中聚合函数的使用类似package com.sw.demo.stream; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Optional; /** * 3.聚合(max/min/count) */ public class polymerization03 { public static void main(String[] args) { //例1:获取String集合中最长的元素 List<String> list = Arrays.asList("abc", "dcdf", "nihao", "xiexieni", "hello"); Optional<String> max = list.stream().max(Comparator.comparing(String::length)); //System.out.println("最长的元素为:" + max); //例2:获取最大值,并按自定义格式排序 List<Integer> list2 = Arrays.asList(1, 55, 22, 8, 90, 777, 45); //自然排序 Optional<Integer> max01 = list2.stream().max(Integer::compareTo); //自定义排序 Optional<Integer> max02 = list2.stream().max(new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o1.compareTo(o2); } }); //System.out.println("自然排序" + max01); //System.out.println("自定义排序" + max02); //例3:获取员工工资最高的人(同理获取String集合中最长的元素) //例4:计算集合中有几个大于6的数 List<Integer> list4 = Arrays.asList(5, 6, 8, 1, 2, 55, 22); long count = list4.stream().filter(x -> x > 6).count(); System.out.println(count); } } 四、映射 map/flatMapmap:接收一个函数作为参数该函数会被应用到每个元素上并将其映射成一个新的元素flatMap:接收一个函数作为参数,并将流中的每个值都换成另一个流,然后把所有流连接成一个新的流package com.sw.demo.stream; import com.sw.demo.pojo.Person; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** * 4.映射(map/flatMap) * 映射可以将一个流的元素按照一定的规则映射到另一个流中 * map:接受一个函数作为参数,该函数会被应用到每个函数上,并将其映射成一个新的函数 * flatMap:接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流 */ public class mapping04 { public static void main(String[] args) { //例1:将数组元素转换为大写/每个元素+3 String[] str = {"abc", "bde", "cfg"}; List<String> list01 = Arrays.stream(str).map(String::toUpperCase).collect(Collectors.toList()); List<Integer> list02 = Arrays.asList(1, 2, 3, 6, 7); List<Integer> plus = list02.stream().map(x -> x + 3).collect(Collectors.toList()); //System.out.println("字符转换为大写:" + list01); //System.out.println("每个值+3:" + plus); //例2:每个员工的薪资上涨1000 List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 18, "male", "昆明")); personList.add(new Person("Jack", 7000, 19, "male", "楚雄")); personList.add(new Person("Lily", 7800, 20, "female", "楚雄")); personList.add(new Person("Anni", 8200, 21, "female", "大理")); personList.add(new Person("Owen", 9500, 22, "male", "昆明")); personList.add(new Person("Alisa", 7900, 22, "female", "保山")); //不改变原来员工集合的方式 List<Person> newPersonList = personList.stream().map(person -> { Person newPerson = new Person(person.getName(), 0, 0, null, null); newPerson.setSalary(person.getSalary() + 1000); return newPerson; }).collect(Collectors.toList()); //System.out.println("改动前:" + personList.get(0).getName() + "----->" + personList.get(0).getSalary()); //System.out.println("改动后:" + newPersonList.get(0).getName() + "----->" + newPersonList.get(0).getSalary()); //改变了原来员工集合的方式 List<Person> newPersonList1 = personList.stream().map(person -> { person.setSalary(person.getSalary() + 1000); return person; }).collect(Collectors.toList()); //System.out.println("二次改动前:" + personList.get(0).getName() + "----->" + personList.get(0).getSalary()); //System.out.println("二次改动后:" + newPersonList1.get(0).getName() + "----->" + newPersonList1.get(0).getSalary()); /* 二次改动前:Tom----->9900(直接在personList的基础上操作,没有new对象) 二次改动后:Tom----->9900 */ //例3:将两个字符串合并为1个新的字符串 List<String> list03 = Arrays.asList("a,s,a,s", "a,s,1,2,d"); List<String> newList03 = list03.stream().flatMap(s -> { //将每个元素转换为一个stream String[] split = s.split(","); Stream<String> s01 = Arrays.stream(split); return s01; }).collect(Collectors.toList()); System.out.println("处理集合前:" + list03); System.out.println("处理集合后:" + newList03); /* 处理集合前:[a,s,a,s, a,s,1,2,d] 处理集合后:[a, s, a, s, a, s, 1, 2, d] */ } } 五、归约 reduce把一个流缩减成一个值,实现对集合的求和、乘积、最值等操作package com.sw.demo.stream; import com.sw.demo.pojo.Person; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Optional; /** * 5.规约 * 规约也称缩减,即把一个流缩减为一个值,实现对集合求和、乘积、最值 */ public class reduce05 { public static void main(String[] args) { //例1: List<Integer> list = Arrays.asList(5, 8, 88, 9, 555); //求和方式一: Optional<Integer> sum1 = list.stream().reduce((x, y) -> x + y); //求和方式二: Optional<Integer> sum2 = list.stream().reduce(Integer::sum); //求和方式三: Integer sum3 = list.stream().reduce(0, Integer::sum); //乘积 Optional<Integer> product = list.stream().reduce((x, y) -> x * y); //求最大值方式一 Optional<Integer> max1 = list.stream().reduce((x, y) -> x > y ? x : y); //求最大值方式er Integer max2 = list.stream().reduce(1, Integer::max); //System.out.println("求和:" + sum1.get() + "," + sum2.get() + "," + sum3); //System.out.println("乘积:" + product.get()); //System.out.println("最值:" + max1 + "," + max2); //例2:求所有员工的工资之和,最高工资 List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 18, "male", "昆明")); personList.add(new Person("Jack", 7000, 19, "male", "楚雄")); personList.add(new Person("Lily", 7800, 20, "female", "楚雄")); personList.add(new Person("Anni", 8200, 21, "female", "大理")); personList.add(new Person("Owen", 9500, 22, "male", "昆明")); personList.add(new Person("Alisa", 7900, 22, "female", "保山")); //求和1: Optional<Integer> s1 = personList.stream().map(Person::getSalary).reduce(Integer::sum); //方式2: Integer s2 = personList.stream().reduce(0, (s, p) -> s += p.getSalary(), (sa1, sa2) -> sa1 + sa2); //方式3: Integer s3 = personList.stream().reduce(0, (s, p) -> s += p.getSalary(), Integer::sum); //求工资最高的人方式一 Integer smax1 = personList.stream().reduce(0, (m, p) -> m > p.getSalary() ? m : p.getSalary(), Integer::max); //求工资最高的人方式二 Integer smax2 = personList.stream().reduce(0, (m, p) -> m > p.getSalary() ? m : p.getSalary(), (x, y) -> x > y ? x : y); System.out.println("工资之和:"+s1+","+s2+","+s3); System.out.println("工资最值:"+smax1+","+smax2); } } 六、收集 collect1.归集 toList/toSet/toMap因为流不存储数据,在流中的数据处理完之后,要将流中的数据重新归到新的集合里package com.sw.demo.stream; import com.sw.demo.pojo.Person; import java.util.*; import java.util.stream.Collectors; /** * 6.收集(collect) * 将流收集为一个值或一个新的集合 * collect主要依赖java.util.stream.Collectors类内置的静态方法 */ public class collect01 { public static void main(String[] args) { /* 6.1 归集:因为流不存储数据,在流中的数据处理完之后,需要将流中的数据重新归集到新的集合里 toList(),toSet(),toMap() */ //toList/toSet List<Integer> list = Arrays.asList(1, 6, 3, 4, 6, 7, 9, 6, 20); List<Integer> newList = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toList()); //去重 Set<Integer> newSet = list.stream().filter(x -> x % 2 == 0).collect(Collectors.toSet()); List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 18, "male", "昆明")); personList.add(new Person("Jack", 7000, 19, "male", "楚雄")); personList.add(new Person("Lily", 7800, 20, "female", "楚雄")); personList.add(new Person("Anni", 8200, 21, "female", "大理")); personList.add(new Person("Owen", 9500, 22, "male", "昆明")); personList.add(new Person("Alisa", 7900, 22, "female", "保山")); Map<?, Person> map = personList.stream().filter(p -> p.getSalary() > 8000).collect(Collectors.toMap(Person::getName, p -> p)); System.out.println("toList:" + newList); //toList:[6, 4, 6, 6, 20] System.out.println("toSet" + newSet); //toSet[4, 20, 6] System.out.println("toMap:" + map); //key:name - value:Person } } 2.统计 count/averagingCollectors提供了一系列用于数据统计的静态方法计数 count平均值 averagingInt,averagingLong,averagingDouble最值 maxBy,minBy求和 summingInt,summingLong,summingDouble统计以上所有 summarizingInt,summarizingLong,summarizingDoublepackage com.sw.demo.stream; import com.sw.demo.pojo.Person; import java.util.*; import java.util.stream.Collectors; /** * 6.2 统计(count/averaging) * 计数 count * 平均值 averagingInt averagingLong averagingDouble * 最值 maxBy minBy * 求和 summingInt summingLong summingDouble * 统计以上所有 summarizingInt summarizingLong summarizingDouble */ public class collect02 { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 18, "male", "昆明")); personList.add(new Person("Jack", 7000, 19, "male", "楚雄")); personList.add(new Person("Lily", 7800, 20, "female", "楚雄")); personList.add(new Person("Anni", 8200, 21, "female", "大理")); personList.add(new Person("Owen", 9500, 22, "male", "昆明")); personList.add(new Person("Alisa", 7900, 22, "female", "保山")); //求总数 Long count = personList.stream().collect(Collectors.counting()); //平均工资 Double salary = personList.stream().collect(Collectors.averagingDouble(Person::getSalary)); //最高工资 Optional<Integer> max = personList.stream().map(Person::getSalary).collect(Collectors.maxBy(Integer::compareTo)); //工资之和 Integer sum = personList.stream().collect(Collectors.summingInt(Person::getSalary)); //统计所有信息 DoubleSummaryStatistics collect = personList.stream().collect(Collectors.summarizingDouble(Person::getSalary)); System.out.println("员工总数:" + count); System.out.println("平均工资:" + salary); System.out.println("最高工资:" + max); System.out.println("工资之和:" + sum); System.out.println("所有信息:" + collect); } } 3.分组 partitioningBy/groupingBy分区:将stream按条件分为两个map,例:按性别将员工分组分组:将集合分为多个map,例:按地区分组package com.sw.demo.stream; import com.sw.demo.pojo.Person; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.stream.Collector; import java.util.stream.Collectors; /** * 6.3 分组(partitioningBy/groupingBy) * 分区:将stream按条件分为两个Map * 分组:将集合分为多个Map,如按部门,地区分组 */ public class collect03 { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 18, "male", "昆明")); personList.add(new Person("Jack", 7000, 19, "male", "楚雄")); personList.add(new Person("Lily", 7800, 20, "female", "楚雄")); personList.add(new Person("Anni", 8200, 21, "female", "大理")); personList.add(new Person("Owen", 9500, 22, "male", "昆明")); personList.add(new Person("Alisa", 7900, 22, "female", "保山")); //按员工薪资高于8000分组 key:boolean - value:List Map<Boolean, List<Person>> part = personList.stream().collect(Collectors.groupingBy(x -> x.getSalary() > 8000)); //按性别分组 key:String - value:List Map<String, List<Person>> sex = personList.stream().collect(Collectors.groupingBy(Person::getSex)); //先按性别分组,再按地区分组 key:String - value:Map Map<String, Map<String, List<Person>>> area = personList.stream().collect(Collectors.groupingBy(Person::getSex, Collectors.groupingBy(Person::getArea))); System.out.println("薪资高于8000的员工:"+part); System.out.println("按性别分组:"+sex); System.out.println("按地区分组:"+area); } } 4.接合 joining将stream中的元素用特定的连接符连接成一个字符串(如果没有连接符,则直接连接)package com.sw.demo.stream; import java.util.Arrays; import java.util.List; import java.util.stream.Collector; import java.util.stream.Collectors; /** * 6.4 接合(joining) * joining可以将stream中的元素用特定的连接符连接成一个字符串(如果没有连接符,则直接连接) */ public class collect04 { public static void main(String[] args) { List<String> list = Arrays.asList("a", "1", "b", "2", "c", "3", "d", "4"); String joining = list.stream().collect(Collectors.joining("-->")); System.out.println(joining); } } 5.归约 reducingCollectors类提供的reducing方法,相比于stream本身的reduce方法,增加了对自定义归约的支持package com.sw.demo.stream; import com.sw.demo.pojo.Person; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** * 6.5 规约(reducing) * Collectors类提供的reducing方法相较于stream本身的reduce方法,增加了对自定义规约的支持 */ public class collect05 { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 18, "male", "昆明")); personList.add(new Person("Jack", 7000, 19, "male", "楚雄")); personList.add(new Person("Lily", 7800, 20, "female", "楚雄")); personList.add(new Person("Anni", 8200, 21, "female", "大理")); personList.add(new Person("Owen", 9500, 22, "male", "昆明")); personList.add(new Person("Alisa", 7900, 22, "female", "保山")); //每位员工增加50块奖金,求发奖金之后所有员工的薪资之和 Integer sum = personList.stream().collect(Collectors.reducing(0, Person::getSalary, (x, y) -> (x + y + 50))); System.out.println("发奖金之后的薪资之和:" + sum); //stream的reduce方法,求员工薪资之和 Optional<Integer> reduceSum = personList.stream().map(Person::getSalary).reduce(Integer::sum); System.out.println("员工薪资之和(reduce方法):"+reduceSum); } } 七、排序 sortedsorted():自然排序,流中元素需实现Comparable接口sorted(Comparator com):自定义排序package com.sw.demo.stream; import com.sw.demo.pojo.Person; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; /** * 7 排序(sort) * sorted():自然排序,流中元素实现Comparable接口 * sorted(Comparator com):Comparator排序器实现自定义排序 */ public class sorted07 { public static void main(String[] args) { List<Person> personList = new ArrayList<Person>(); personList.add(new Person("Tom", 8900, 18, "male", "昆明")); personList.add(new Person("Jack", 7000, 19, "male", "楚雄")); personList.add(new Person("Lily", 7800, 20, "female", "楚雄")); personList.add(new Person("Anni", 8900, 21, "female", "大理")); personList.add(new Person("Owen", 9500, 22, "male", "昆明")); personList.add(new Person("Alisa", 7900, 22, "female", "保山")); //例:按薪资排序(工资相同的按年龄比较) //升序排列(自然排序) List<String> listASC = personList.stream().sorted(Comparator.comparing(Person::getSalary)).map(Person::getName).collect(Collectors.toList()); //降序排列(升序反转即为降序) List<String> listDESC = personList.stream().sorted(Comparator.comparing(Person::getSalary).reversed()).map(Person::getName).collect(Collectors.toList()); //先按工资,再按年龄升序排列(升序) List<String> listASC01 = personList.stream().sorted(Comparator.comparing(Person::getSalary).thenComparing(Person::getAge)).map(Person::getName).collect(Collectors.toList()); //先按工资再按年龄自定义排序(降序) /* debug流程(降序):两两比较,a>b,a存起来,b继续跟c比较,如果b<c,则继续比较a、c两个数,否则反之 */ List<String> diy = personList.stream().sorted((p1, p2) -> { if (p1.getSalary() == p2.getSalary()) { //System.out.println(p2.getAge() - p1.getAge()); return p2.getAge() - p1.getAge(); } else { //System.out.println(p2.getSalary() - p1.getSalary()); return p2.getSalary() - p1.getSalary(); } }).map(Person::getName).collect(Collectors.toList()); System.out.println("自然排序:"+listASC); System.out.println("工资降序:"+listDESC); System.out.println("先按工资再按年龄自然排序:"+listASC01); System.out.println("自定义排序:"+diy); } } 八、提取/组合concat合并,distinct去重,limit限制,skip跳过package com.sw.demo.stream; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** * 8.提取/组合 * 对流进行合并、去重(distinct)、限制(limit)、跳过(skip)等操作 */ public class extract08 { public static void main(String[] args) { String[] arr1 = {"a", "b", "d", "r", "a"}; String[] arr2 = {"g", "r", "d", "b", "c"}; Stream<String> stream1 = Stream.of(arr1); Stream<String> stream2 = Stream.of(arr2); //合并两个流,并去重 List<String> concatDistinct = Stream.concat(stream1, stream2).distinct().collect(Collectors.toList()); //limit 限制只能从流中获取前n个数 List<Integer> limit = Stream.iterate(1, x -> x + 1).limit(10).collect(Collectors.toList()); //skip 跳过前n个数据,注:需加上limit限制,否则iterate构造器会一直创建数据 List<Integer> skip = Stream.iterate(1, x -> x + 2).skip(1).limit(5).collect(Collectors.toList()); System.out.println("合并流:" + concatDistinct); System.out.println("限制只能从流中获取前10个数:" + limit); System.out.println("跳过第一个数据:" + skip); } } 注:全文参考https://blog.csdn.net/mu_wind/article/details/109516995
2021年02月05日
302 阅读
0 评论
0 点赞
2021-01-06
集合不安全问题
集合类不安全List不安全package com.sw.unsafe; import java.util.*; import java.util.concurrent.CopyOnWriteArrayList; /** * @Author suaxi * @Date 2021/1/4 17:12 * java.util.ConcurrentModificationException 并发修改异常 */ public class ListTest { public static void main(String[] args) { /* 并发情况下ArrayList不安全 解决方案: 1、List<String> list = new Vector<>(); 2、List<String> list = Collections.synchronizedList(new ArrayList<>()); 3、List<String> list = new CopyOnWriteArrayList<>(); CopyOnWrite 写入时复制(是一种优化策略) 多个线程调用的时候可能存在写入覆盖问题,读取没问题 CopyOnWrite在写入的时候复制一份给调用者,调用者写入新的数据完成之 后再把之前复制的数据放回原来的位置,保证线程的安全,以此避免了写入覆盖问题 相较于Vector,它没有采用synchronized锁,而是采用Lock锁,效率更高 */ List<String> list = new CopyOnWriteArrayList<>(); for (int i = 0; i < 100; i++) { new Thread(() ->{ list.add(UUID.randomUUID().toString().substring(0,5)); System.out.println(list); },String.valueOf(i)).start(); } } } Set不安全package com.sw.unsafe; import java.util.*; import java.util.concurrent.CopyOnWriteArraySet; /** * @Author suaxi * @Date 2021/1/4 22:08 * java.util.ConcurrentModificationException 并发修改异常 * 解决方法: * 1、Set<String> set = Collections.synchronizedSet(new HashSet<>()); * 2、Set<String> set = new CopyOnWriteArraySet<>(); */ public class SetTest { public static void main(String[] args) { Set<String> set = new CopyOnWriteArraySet<>(); for (int i = 0; i < 30; i++) { new Thread(() ->{ set.add(UUID.randomUUID().toString().substring(0,5)); System.out.println(set); },String.valueOf(i)).start(); } } } hashSet底层是什么?public HashSet(){ map = new HashMap<>(); } //源码 //set add的本质就是map public boolean add(E e) { return map.put(e, PRESENT)==null; } //PRESENT是静态终类 private static final Object PRESENT = new Object();Map不安全package com.sw.unsafe; import java.util.HashMap; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; /** * @Author suaxi * @Date 2021/1/4 22:26 * java.util.ConcurrentModificationException * 解决方法: * Map<String, String> map = new ConcurrentHashMap<>(); */ public class MapTest { public static void main(String[] args) { //默认等价于? new HashMap<>(16,0.75); Map<String, String> map = new ConcurrentHashMap<>(); for (int i = 0; i < 30; i++) { new Thread(() ->{ map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,5)); System.out.println(map); },String.valueOf(i)).start(); } } }
2021年01月06日
631 阅读
0 评论
0 点赞
1
...
34
35
36
...
55