java8?Stream大數(shù)據(jù)量List分批處理切割方式
java8 Stream大數(shù)據(jù)量List分批處理
//按每3個(gè)一組分割 private static final Integer MAX_NUMBER = 3; /** * 計(jì)算切分次數(shù) */ private static Integer countStep(Integer size) { ?? ?return (size + MAX_NUMBER - 1) / MAX_NUMBER; } public static void main(String[] args) { ? ? ? List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7); ? ? ? int limit = countStep(list.size()); ? ? ? //方法一:使用流遍歷操作 ? ? ? List<List<Integer>> mglist = new ArrayList<>(); ? ? ? Stream.iterate(0, n -> n + 1).limit(limit).forEach(i -> { ? ? ? ? ? mglist.add(list.stream().skip(i * MAX_NUMBER).limit(MAX_NUMBER).collect(Collectors.toList())); ? ? ? }); ? ? ? System.out.println(mglist); ? ? ? //方法二:獲取分割后的集合 ? ? ? List<List<Integer>> splitList = Stream.iterate(0, n -> n + 1).limit(limit).parallel().map(a -> list.stream().skip(a * MAX_NUMBER).limit(MAX_NUMBER).parallel().collect(Collectors.toList())).collect(Collectors.toList()); ? ? ?? ? ? ? System.out.println(splitList); }
使用google guava對List進(jìn)行分割
//使用guava對list進(jìn)行分割 List<User> users = userService.findAll(); //按每50個(gè)一組分割 List<List<User>> parts = Lists.partition(users, 50); parts.stream().forEach(list -> { ? ? process(list); });
使用apache common collection
List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8); List<List<Integer>> subs = ListUtils.partition(intList, 3);
java 手寫將一個(gè)List等分成n個(gè)list
public static <T> List<List<T>> averageAssign(List<T> source, int n) { ? ? List<List<T>> result = new ArrayList<>(); ?? ?//(先計(jì)算出余數(shù)) ? ? int remainder = source.size() % n; ? ? ? //然后是商 ? ? int number = source.size() / n; ? ?? ?//偏移量 ? ? int offset = 0; ? ? for (int i = 0; i < n; i++) { ? ? ? ? List<T> value; ? ? ? ? if (remainder > 0) { ? ? ? ? ? ? value = source.subList(i * number + offset, (i + 1) * number + offset + 1); ? ? ? ? ? ? remainder--; ? ? ? ? ? ? offset++; ? ? ? ? } else { ? ? ? ? ? ? value = source.subList(i * number + offset, (i + 1) * number + offset); ? ? ? ? } ? ? ? ? result.add(value); ? ? } ? ? return result; }
java8部分特性及l(fā)ist的常見操作
主要記錄如何使用Java8中的流式處理,簡潔的處理各種常見的操作。
注意:
數(shù)組轉(zhuǎn)集合,體現(xiàn)的是適配器模式,只是轉(zhuǎn)換接口,后臺的數(shù)據(jù)仍是數(shù)組。所以使用集合相關(guān)的操作add、remove、clear會拋異常:UNSupportOperationException。
List<String> list = Arrays.asList("官僚","買辦","資產(chǎn)階級");
集合轉(zhuǎn)數(shù)組,不能直接使用無參toArray()方法,該方法返回的是Object[],若強(qiáng)轉(zhuǎn)可能會存在轉(zhuǎn)換異常。帶參的大小,必須要跟集合list保持一致,否則會涉及重新分配內(nèi)存。
Lambda表達(dá)式
- 格式(params) -> {expression}
- 比如我們實(shí)現(xiàn)一個(gè)Runnable接口
Runnable run = new Runnable() { ?? ?@Override ?? ?public void run() { ?? ??? ?// TODO ?? ?} }
使用Lambda表達(dá)式:Runnable run = () -> {# TODO}
函數(shù)式接口,規(guī)范:
- 接口中只能有一個(gè)抽象方法
- (可選)在接口上添加@FunctionalInterface注解,這樣可以檢驗(yàn)它是否一個(gè)函數(shù)式接口
比如:
@FunctionalInterface public interface MyFun { ?? ?void fun(); } //也可以使用泛型 @FunctionalInterface public interface MyFun1<T> { ?? ?void fun(T t); }
使用的時(shí)候
public static void domething(MyFun myfun) { ?? ?myfun.fun(); } public static void domething(MyFun1<User> myFun) { ?? ?User user = new User(); ?? ?user.setName("我是泛型"); ?? ?myFun.fun(user); } public static void main(String[] args) { ?? ?domething(() -> {System.out.println("通過lambda表達(dá)式執(zhí)行了函數(shù)式接口");}); ?? ?domething1((item) -> { ?? ??? ?item.setId(100); ?? ??? ?item.setAge(20); ?? ??? ?System.out.println("這是MyFun1函數(shù)式接口真正的執(zhí)行邏輯,最終的結(jié)果是:" + JsonObject.toJsonString(item);) ?? ?}); }
常見的list操作
/** ?* 數(shù)組轉(zhuǎn)集合,體現(xiàn)的是適配器模式,只是轉(zhuǎn)換接口,后臺的數(shù)據(jù)仍是數(shù)組。 ?* 所以使用集合相關(guān)的操作add/remove/clear會拋錯(cuò):unSupportOperationException ?* ?*/ List<String> arrList = Arrays.asList("買辦", "資產(chǎn)階級", "官僚"); /** ?* 集合轉(zhuǎn)數(shù)組,不能直接使用無參toArray()方法,該方法的返回類型是Object[],若強(qiáng)轉(zhuǎn),可能存在轉(zhuǎn)換異常 ?* 帶參的大小,必須要跟集合list保持一致,否則會涉及內(nèi)存的重新分配 ?*/ List<String> list = new ArrayList<>(); list.add("買辦"); list.add("官僚"); list.add("資產(chǎn)階級"); // 注意:大小必須和list保持一致,若小于3,則需要重新分配內(nèi)存地址,并返回新數(shù)組地址; // 若數(shù)組元素大于所需,則下標(biāo)為[list.size()]的元素置為null,其他元素為原值 // 所以最好將數(shù)組大小跟集合大小保持一致,可以驗(yàn)證new String[1],new String[5]的輸出值 String[] arr = new String[list.size()]; arr = list.toArray(arr); System.out.println("arr :" + Arrays.toString(arr)); // list 初始化(guava) List<String> initList = Lists.newArrayList("Java", "Python", "Javascript"); List<User> students = new ArrayList<>(); User st1 = new User(); st1.setId(123); st1.setAge(10); User st2 = new User(); st2.setId(123); st2.setAge(20); User st3 = new User(); st3.setId(456); st3.setAge(20); students.add(st1); students.add(st2); students.add(st3); // list 分割(guava) List<List<User>> splits = Lists.partition(students, 2); System.out.println("list分割:" + JsonUtil.toJSONString(splits)); // list分組 Map<Integer, List<User>> groupStu = students.stream().collect( ? ? ? ? Collectors.groupingBy(User::getAge)); System.out.println("list分組:" + JsonUtil.toJSONString(groupStu)); // list轉(zhuǎn)map, (k,v),若集合中有重復(fù)的key,會拋異常:Duplicate key…… // 通過(k1, k2)->k1來處理重復(fù)情況,保留k1,舍棄k2 Map<Integer, Integer> studentIdMap = students.stream().collect( ? ? ? ? Collectors.toMap(User::getId, User::getAge, (k1, k2) -> k1)); System.out.println("list轉(zhuǎn)map, (k,v) :" + studentIdMap); // list轉(zhuǎn)map, (k,t) Map<Integer, User> studenteMap = students.stream().collect( ? ? ? ? Collectors.toMap(User::getId, Function.identity(), (k1, k2) -> k1)); System.out.println("list轉(zhuǎn)map, (k,t) :" + studenteMap); // list過濾 List<User> oldStu = students.stream().filter( ? ? ? ? student -> student.getAge() > 10).collect(Collectors.toList()); System.out.println("list過濾filter :" + JsonUtil.toJSONString(oldStu)); // list對象轉(zhuǎn)換 List<Teacher> teachers = students.stream().map( ? ? ? ? student -> { ? ? ? ? ? ? Teacher teacher = new Teacher(); ? ? ? ? ? ? BeanUtils.copyProperties(student, teacher); ? ? ? ? ? ? teacher.setTitle("教師"); ? ? ? ? ? ? return teacher; ? ? ? ? }).collect(Collectors.toList()); System.out.println("list對象轉(zhuǎn)化:" + JsonUtil.toJSONString(teachers)); // list轉(zhuǎn)set Set<Integer> ages = students.stream().map(User::getAge).collect(Collectors.toSet()); System.out.println("list轉(zhuǎn)set:" + ages); // 過濾掉空元素后再map ? ? public static void main(String[] args) { ? ? ? ? List<Customer> customerList = new ArrayList<>(); ? ? ? ? customerList.add(new Customer(1L, "Ryu")); ? ? ? ? customerList.add(new Customer(2L, "Ken")); ? ? ? ? customerList.add(new Customer(3L, null)); ? ? ? ? customerList.add(null); ? ? ? ? customerList.add(new Customer(5L, null)); ? ? ? ? customerList.add(new Customer(6L, "Zangief")); ? ? ? ?? ? ? ? ?? ? ? ? ? List<String> nameList1 = customerList.stream() ? ? ? ? ? ? ? ? .filter(Objects::nonNull) // 過濾掉Customer為null的元素 ? ? ? ? ? ? ? ? .map(e -> e.getName()) ? ? ? ? ? ? ? ? ? ? .filter(Objects::nonNull) // 過濾掉Customer.getName()為null的元素 ? ? ? ? ? ? ? ? .collect(Collectors.toList()); ? ? ? ?? ? ? ? ?? ? ? ? ? System.out.println(nameList1); // [Ryu, Ken, Zangief] ? ? ? ?? ? ? }
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Spring?Boot?如何通過ServletRequestHandledEvent事件實(shí)現(xiàn)接口請求的性能監(jiān)控
在Spring框架中,監(jiān)控接口請求的性能可以通過ServletRequestHandledEvent事件實(shí)現(xiàn),這篇文章給大家介紹Spring?Boot?如何通過ServletRequestHandledEvent事件實(shí)現(xiàn)接口請求的性能監(jiān)控,感興趣的朋友跟隨小編一起看看吧2024-08-08Spring線程池ThreadPoolTaskExecutor配置詳情
本篇文章主要介紹了Spring線程池ThreadPoolTaskExecutor配置詳情,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-03-03詳解Java中方法next()和nextLine()的區(qū)別與易錯(cuò)點(diǎn)
這篇文章主要介紹了詳解Java中方法next()和nextLine()的區(qū)別與易錯(cuò)點(diǎn),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11關(guān)于springboot中對sqlSessionFactoryBean的自定義
這篇文章主要介紹了springboot中對sqlSessionFactoryBean的自定義方式,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12springIOC的使用流程及spring中使用類型轉(zhuǎn)換器的方式
Spring IOC是Spring框架的核心原理之一,它是一種軟件設(shè)計(jì)模式,用于管理應(yīng)用程序中的對象依賴關(guān)系,這篇文章主要介紹了springIOC的使用流程以及spring中如何使用類型轉(zhuǎn)換器,需要的朋友可以參考下2023-06-06