jdk1.8 集合操作



import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import java.io.*;
import java.text.Collator;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * JDK1.8的学习
 */

public class jdk8 {

   public static void main(String[] args)
   {

       //一. jdk1.8 lamda表达式及stream流操作学习
       //       1.对象创建: 使用lombok注解
       //       @Data
       //       @NoArgsConstructor
       //       @AllArgsConstructor

       //1.1 集合浅复制: 仅复制它自己这个对象,不复制它所引用的对象
       //List<CustomInfParamBO> delList = new ArrayList<>(customInfParamList);
       //1.2 集合深复制: 复制要复制的对象和它所引用的对象,可以使用序列化方式(对象要实现序列化)
       /*public List copyBySerialize(List source) throws IOException, ClassNotFoundException{
            ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
            ObjectOutputStream out = new ObjectOutputStream(byteOut);
            out.writeObject(source);
        
            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            ObjectInputStream in =new ObjectInputStream(byteIn);
            List dest = (List)in.readObject();
            return dest;
        }*/

       //1.2 单个对象创建list
       //Arrays.asList(itcabinetBO);

       //2. list或者map创建
       Map<String, Integer> map = Maps.newHashMap();
       List<Map.Entry<String, Integer>> dataList = Lists.newArrayList(map.entrySet());

       //3.1 list转map
       //List<RankVo> list1 =  Lists.newArrayList();
       //Map<String, RankVo> appleMap = list1.stream().collect(Collectors.toMap(RankVo::getModelLabel, e -> e,(k1,k2)->k1));
       //Map<String, String> dataIdLogicIdMap = list1.stream().collect(Collectors.toMap(e -> e.getModelLabel(), e -> e.getName(), (k1, k2) -> k1));
       //list转map防止空指针异常
       //Map<String, String> memberMap = list.stream().collect(HashMap::new, (m,v)->m.put(v.getId(), v.getImgPath()),HashMap::putAll);
       //list转linkedHashmap


       //3.2 list统计后转map
       //List<DevicesInPlaceVo> devicesInPlaceVos = Lists.newArrayList();
       //Map<String, Integer> peceventcountTypeMap = new HashMap<>(16);
       //devicesInPlaceVos.stream().forEach(e -> peceventcountTypeMap.merge(e.getModelLabel(),e.getId().intValue(), Integer::sum));


       //3.3 list对象中取某字段
       //List<String> modelLabelList = list1.stream().map(RankVo::getModelLabel).collect(Collectors.toList());

       //3.4 list分组转map
      // Map<String, List<RankVo>> rankMap = list1.stream().collect(Collectors.groupingBy(RankVo::getModelLabel));

       //3.5 list分组统计
       //Map<String, Long> countMap = list1.stream().collect(Collectors.groupingBy(RankVo::getModelLabel, Collectors.counting()));

        //4.1 list对象单字段去重
       //List<RemoteCtrDrivePushBO> finalContentList = contentList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()-> new TreeSet<>(Comparator.comparing(RemoteCtrDrivePushBO::getId))), ArrayList::new));
       //4.2 list对象多字段去重
       //List<Order> orders = Lists.newArrayList();
       //orders = orders.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(()-> new TreeSet<>(Comparator.comparing(o -> o.getNum() + ";" + o.getType()))), ArrayList::new));

       //4.3.字段筛选,去重
       List list = Lists.newArrayList();
       //List<Long> deviceIds = list3.stream().map(e -> e.getMeasuredby()).distinct().collect(Collectors.toList());

       //5.集合枚举
       List<String> EVENT_LEVEL_IN_STRING = Stream.of("事故", "告警", "一般", "预警", "其他").collect(Collectors.toList());

       //6.list分类
       //List<ThresholdStrategy> thresholdStrategys = Lists.newArrayList();
       //Map<Long, ThresholdStrategy> idStrategyMap = thresholdStrategys.stream().collect(Collectors.toMap(ThresholdStrategy::getId, s -> s));

       //7.统计
       //List<Map> queryList =  Lists.newArrayList();
       //int count = queryList.stream().mapToInt(e -> e.get("count").sum();

       //8.过滤,取均值
       //最大值
       //Double maxuabValue = allList.stream().filter(e -> e.get("uab") != null).mapToDouble(e -> (Double) e.get("uab")).max().getAsDouble();
       // 最小值
       //Double minuabValue = allList.stream().filter(e -> e.get("uab") != null).mapToDouble(e -> (Double) e.get("uab")).min().getAsDouble();
       // 平均值
       //Double averageuabValue = allList.stream().filter(e -> e.get("uab") != null).mapToDouble(e -> (Double) e.get("uab")).average().getAsDouble();

       //9.查找任何一个
       //DevicesInPlaceVo dcbaseDeviceInfo = devicesInPlaceVos.stream().findAny().orElse(null);

       //10.统计字段总数
       //List<PecEventCountVo> pecEventCountVos = Lists.newArrayList();
       //int totalCount = pecEventCountVos.stream().collect(Collectors.summingInt(vo -> (vo.getCount())));

       //11.排序
       //Collections.sort(pecEventCountVos, Comparator.comparing(PecEventCountVo::getDeviceid));
       //12.自定义排序,为null放最后面
       Collections.sort(list, new Comparator<Integer>() {
           @Override
           public int compare(Integer o1, Integer o2) {
               if (o1 != null && o2 != null) {
                   return o1.compareTo(o2);
               } else {
                   return o1 == null ? 1 : -1;
               }
           }
       });

       //12.map遍历,list遍历
       Map<String,Object> peceventtypeMap = Maps.newHashMap();
       peceventtypeMap.forEach((key,val)->{

       });

       //list1.forEach(e->{

       //});

       //13.list,map并集,适用于递归计算
       //list1.addAll(list1);
       peceventtypeMap.putAll(peceventtypeMap);

       //14.map的value没值时取默认值,避免null值
       //peceventcountTypeMap.getOrDefault("key", 0);

       //15.Collections优雅的返回空list,空set,空map
       Collections.emptyList();
       Collections.emptySet();
       Collections.emptyMap();

       //16.objects优雅判断null或者相等
       Objects.nonNull("123");
       Objects.isNull("66");
       Objects.equals("a","b");

       //17.判断为true
       //BooleanUtils.isTrue(s.getIsTemplate();

       //18.list多字段中文排序,排序规则->中文拼音首字母
       List <Map> list3 = Lists.newArrayList();
       Collections.sort(list3, new Comparator<Map>() {
           @Override
           public int compare(Map o1, Map o2) {
               Comparator<Object> com1 = Collator.getInstance(Locale.CHINA);
               Comparator<Object> com2 = Collator.getInstance(Locale.CHINA);
               int c = com1.compare(o1.get("deviceTypeName"), o2.get("deviceTypeName"));
               if (c != 0) {
                   return c;
               }
               return com2.compare(o1.get("name"), o2.get("name"));
           }
       });

       //19.集合order和limit
       //升序
       //List<ItcabinetBO> top5Cabinets = itcabinetBOs.stream().sorted(Comparator.comparing(ItcabinetBO::getUsedUnitRate)).limit(5).collect(Collectors.toList());
       //降序
       //List<ItcabinetBO> top5Cabinets = itcabinetBOs.stream().sorted(Comparator.comparing(ItcabinetBO::getUsedUnitRate).reversed()).limit(5).collect(Collectors.toList());

       //20.集合遍历构建新对象
      /*
      List<AssetTypeCountBO> unUsedassetTypeCount = unUsedTypeids.stream().map(id->{
           AssetTypeCountBO  assetTypeCountBO = new AssetTypeCountBO();
           assetTypeCountBO.setAssetTypeName(classifyNameMap.get(id));
           assetTypeCountBO.setAssetTypeCount(0);
           assetTypeCountBO.setAssetTypeId(id);
           return assetTypeCountBO;
       }).collect(Collectors.toList());
       */

      //21.将集合数据按逗号分隔变成字符串
       //StringUtils.join(executeBatteryIds, ",")

       //22.创建线程安全集合
       //Collections.synchronizedList(list)

       //分批次查询
       /*int index = 0, limit = 300;
       while(index < deviceIds.size()){
           int endindex = index+limit;
           if(endindex >= deviceIds.size()){
               endindex = deviceIds.size();
           }
           all.addAll(deviceDataService.queryMeasNodeList(deviceIds.subList(index, endindex), analog).getData());
           index = endindex;
       }*/

       //23 java8删除集合元素
	   ArrayList<String> list =new ArrayList();
       list.addAll(Arrays.asList("curry","tomphson","kerr"));
       list.removeIf(str->str.equals("curry"));
   }

    /**
     *序列化方式实现深拷贝,对象obj需要实现序列化
     * @param obj
     * @param <T>
     * @return
     */
    public static <T extends Serializable> T clone(T obj){
        T cloneObj=null;
        try{
            //写入字节流
            ByteArrayOutputStream baos=new ByteArrayOutputStream();
            ObjectOutputStream oos=new ObjectOutputStream(baos);
            oos.writeObject(obj);
            oos.close();
            //分配内存,写入原始对象,生成新对象
            ByteArrayInputStream bais=new ByteArrayInputStream(baos.toByteArray());//获取上面的输出字节流
            ObjectInputStream ois=new ObjectInputStream(bais);
            //返回生成的新对象
            cloneObj=(T)ois.readObject();
            ois.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return cloneObj;

    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值