首页 > 其他分享 >一些Tools通用工具方法(根据字段过滤相同值的数据、获取富文本中所有图片、list转map等)

一些Tools通用工具方法(根据字段过滤相同值的数据、获取富文本中所有图片、list转map等)

时间:2022-11-11 11:13:17浏览次数:44  
标签:map return String list static new Tools public

package com.ruoyi.util;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.aliyun.helper.AliConst;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.core.domain.BaseEntityPlus;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.SysFileInfo;

import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author Licl
 */
public class Tools {

    public static final Long[] EMPTY_LONG_ARR = {0L};

    public static final String[] EMPTY_STRING_ARR = {""};
    private Object t;

    /**
     * set转数组
     *
     * @param set
     * @return
     */
    public static Long[] set2LongArr(Set<Long> set) {
        if (set.size() > 0) {
            return set.toArray(new Long[set.size()]);
        }
        return EMPTY_LONG_ARR;

    }

    public static String[] set2StrArr(Set<String> set) {
        if (set.size() > 0) {
            return set.toArray(new String[set.size()]);
        }
        return EMPTY_STRING_ARR;
    }

    /**
     * 获取UUID
     *
     * @return UUID
     */
    public static String getUpperCaseUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
    }

    @SuppressWarnings("unchecked")
    public static <K, V> Map<V, K> list2Map(
            @SuppressWarnings("rawtypes") List<? extends BaseEntity> list,
            Function<? super K, ? extends V> mapper) {
        return list
                .stream()
                .filter(e -> mapper.apply((K) e) != null)
                .collect(HashMap::new, (m, v) -> ((Map<K, V>) m).put((K) mapper.apply((K) v), (V) v),
                        HashMap::putAll);
    }

    @SuppressWarnings("unchecked")
    public static <O, K, V> Map<V, K> list2Map(
            @SuppressWarnings("rawtypes") List<? extends BaseEntity> list,
            Function<? super O, ? extends V> key, Function<? super O, ? extends K> value) {
        return list
                .stream()
                .filter(e -> key.apply((O) e) != null)
                .collect(HashMap::new,
                        (m, v) -> ((Map<K, V>) m).put((K) key.apply((O) v), (V) value.apply((O) v)),
                        HashMap::putAll);
    }

    @SuppressWarnings("unchecked")
    public static <K, V> Map<V, K> list2MapPlus(
            @SuppressWarnings("rawtypes") List<? extends BaseEntityPlus> list,
            Function<? super K, ? extends V> mapper) {
        return list
                .stream()
                .filter(e -> mapper.apply((K) e) != null)
                .collect(HashMap::new, (m, v) -> ((Map<K, V>) m).put((K) mapper.apply((K) v), (V) v),
                        HashMap::putAll);
    }

    @SuppressWarnings("unchecked")
    public static <O, K, V> Map<V, K> list2MapPlus(
            @SuppressWarnings("rawtypes") List<? extends BaseEntityPlus> list,
            Function<? super O, ? extends V> key, Function<? super O, ? extends K> value) {
        return list
                .stream()
                .filter(e -> key.apply((O) e) != null)
                .collect(HashMap::new,
                        (m, v) -> ((Map<K, V>) m).put((K) key.apply((O) v), (V) value.apply((O) v)),
                        HashMap::putAll);
    }

    /**
     * 获取随机字符串
     *
     * @param len 字符串你的长度
     * @return
     */
    public static String getRandomJianHan(int len) {
        String ret = "";
        for (int i = 0; i < len; i++) {
            String str = null;
            int hightPos, lowPos;
            Random random = new Random();
            hightPos = (176 + Math.abs(random.nextInt(39)));
            lowPos = (161 + Math.abs(random.nextInt(93)));
            byte[] b = new byte[2];
            b[0] = (new Integer(hightPos).byteValue());
            b[1] = (new Integer(lowPos).byteValue());
            try {
                str = new String(b, "GBK");
            } catch (UnsupportedEncodingException ex) {
                ex.printStackTrace();
            }
            ret += str;
        }
        return ret;
    }

    public static String getName() {
        Random random = new Random();
        String[] surname = {"赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈", "褚", "卫", "蒋", "沈", "韩", "杨", "朱", "秦", "尤", "许",
                "何", "吕", "施", "张", "孔", "曹", "严", "华", "金", "魏", "陶", "姜", "戚", "谢", "邹", "喻", "柏", "水", "窦", "章", "云", "苏", "潘", "葛", "奚", "范", "彭", "郎",
                "鲁", "韦", "昌", "马", "苗", "凤", "花", "方", "俞", "任", "袁", "柳", "酆", "鲍", "史", "唐", "费", "廉", "岑", "薛", "雷", "贺", "倪", "汤", "滕", "殷",
                "罗", "毕", "郝", "邬", "安", "常", "乐", "于", "时", "傅", "皮", "卞", "齐", "康", "伍", "余", "元", "卜", "顾", "孟", "平", "黄", "和",
                "穆", "萧", "尹", "姚", "邵", "湛", "汪", "祁", "毛", "禹", "狄", "米", "贝", "明", "臧", "计", "伏", "成", "戴", "谈", "宋", "茅", "庞", "熊", "纪", "舒",
                "屈", "项", "祝", "董", "梁", "杜", "阮", "蓝", "闵", "席", "季"};
        String girl = "秀娟英华慧巧美娜静淑惠珠翠雅芝玉萍红娥玲芬芳燕彩春菊兰凤洁梅琳素云莲真环雪荣爱妹霞香月莺媛艳瑞凡佳嘉琼勤珍贞莉桂娣叶璧璐娅琦晶妍茜秋珊莎锦黛青倩婷姣婉娴瑾颖露瑶怡婵雁蓓纨仪荷丹蓉眉君琴蕊薇菁梦岚苑婕馨瑗琰韵融园艺咏卿聪澜纯毓悦昭冰爽琬茗羽希宁欣飘育滢馥筠柔竹霭凝晓欢霄枫芸菲寒伊亚宜可姬舒影荔枝思丽 ";
        String boy = "伟刚勇毅俊峰强军平保东文辉力明永健世广志义兴良海山仁波宁贵福生龙元全国胜学祥才发武新利清飞彬富顺信子杰涛昌成康星光天达安岩中茂进林有坚和彪博诚先敬震振壮会思群豪心邦承乐绍功松善厚庆磊民友裕河哲江超浩亮政谦亨奇固之轮翰朗伯宏言若鸣朋斌梁栋维启克伦翔旭鹏泽晨辰士以建家致树炎德行时泰盛雄琛钧冠策腾楠榕风航弘";
        int index = random.nextInt(surname.length - 1);
        String name = surname[index];
        int i = random.nextInt(3);
        int b = 2;
        if (i == b) {
            int j = random.nextInt(girl.length() - 2);
            if (j % b == 0) {
                name = name + girl.substring(j, j + 2);
            } else {
                name = name + girl.substring(j, j + 1);
            }

        } else {
            int j = random.nextInt(girl.length() - 2);
            if (j % b == 0) {
                name = name + boy.substring(j, j + 2);
            } else {
                name = name + boy.substring(j, j + 1);
            }

        }
        return name;
    }

    /**
     * 获取文件URL By List<SysFile>
     *
     * @param list sysFileList
     * @return 拼装好的List
     */
    public static List<SysFileInfo> getFileUrl(List<SysFileInfo> list) {
        list.stream().filter(e -> StringUtils.isNotNull(e.getGroupId())).forEach(e -> {
            e.setFilePath(AliConst.HTTPS + AliConst.BUCKET_NAME + "." + AliConst.ENDPOINT
                    + "/" + AliConst.FILE_DIR + e.getGroupId());
        });
        return list;
    }

    public static String getUpperCaseRandomStr() {
        return UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
    }

    /**
     * 从content中提取一张图片地址作为帖子列表封面图
     * regex:获取<img src="">标签的正则("<img.*?>")
     * content:富文本html内容
     */
    public static String getContentImg(String content) {
        //找到图片标签的正则
        String regex = "<img.*?>";
        //文件可能有多张图片
        List<String> pics = new ArrayList<>();
        try {
            Pattern compile = Pattern.compile(regex);
            Matcher matcher = compile.matcher(content);
            while (matcher.find()) {
                String img = matcher.group();
                //获取src中 "" 图片地址的正则
                String httpUrl = "\"http?(.*?)(\"|>|\\s+)";
                Matcher m = Pattern.compile(httpUrl).matcher(img);
                while (m.find()) {
                    String url = m.group();
                    pics.add(url.substring(1, url.length() - 1));
                    return pics.get(0);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * @return 获取富文本中所有图片
     */
    public static List<String> getContentImgAll(String content) {
        //找到图片标签的正则
        String regex = "<img.*?>";
        //文件可能有多张图片
        List<String> pics = new ArrayList<>();
        try {
            Pattern compile = Pattern.compile(regex);
            Matcher matcher = compile.matcher(content);
            while (matcher.find()) {
                String img = matcher.group();
                //获取src中 "" 图片地址的正则
                String httpUrl = "\"http?(.*?)(\"|>|\\s+)";
                Matcher m = Pattern.compile(httpUrl).matcher(img);
                while (m.find()) {
                    String url = m.group();
                    pics.add(url.substring(1, url.length() - 1));
                    return pics;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pics;
    }

    /**
     * 根据字段过滤相同值的数据
     *
     * @param keyExtractor 需要过滤的字段
     * @param <T>          泛型
     * @return void
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        ConcurrentHashMap<Object, Boolean> map = new ConcurrentHashMap<>();
        return t -> map.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }
}

标签:map,return,String,list,static,new,Tools,public
From: https://www.cnblogs.com/chunwu822/p/16879927.html

相关文章

  • MapReduce实战之小文件处理案例(自定义InputFormat)
    小文件处理案例(自定义InputFormat)1)需求无论hdfs还是mapreduce,对于小文件都有损效率,实践中,又难免面临处理大量小文件的场景,此时,就需要有相应解决方案。将多个小文件合并成一......
  • MapReduce实战之辅助排序和二次排序案例
    辅助排序和二次排序案例1)需求有如下订单数据订单id商品id成交金额0000001Pdt_01222.80000001Pdt_0625.80000002Pdt_03522.80000002Pdt_04122.40000002Pdt_05722.40000003Pdt......
  • MapReduce实战之日志清洗案例
    简单解析版1)需求:去除日志中字段长度小于等于11的日志。2)输入数据   数据有点大3)实现代码:(1)编写LogMapperpackagecom.atguigu.mapreduce.weblog;importjava.io.IOExc......
  • MapReduce实战之 MapReduce中多表合并案例
     MapReduce中多表合并案例1)需求:订单数据表t_order:idpidamount1001011100202210030331001   01   11002   02   21003   03   31004   01 ......
  • MapReduce实战之倒排索引案例(多job串联)
    0)需求:有大量的文本(文档、网页),需要建立搜索索引输出数据:a:atguigupingpingatguigussatguigussb:atguigupingpingatguigupingpingpingpingssc:atguigussatguigup......
  • MapReduce实战之压缩/解压缩案例
    1数据流的压缩和解压缩CompressionCodec有两个方法可以用于轻松地压缩或解压缩数据。要想对正在被写入一个输出流的数据进行压缩,我们可以使用createOutputStream(OutputStr......
  • list容器-链表
    3.7list容器3.7.1list基本概念功能:将数据进行链式存储(链表)链表(list)是一种物理存储单元上非连续的存储结构,数据元素的逻辑顺序是通过链表中的指针链接实现的链表的组......
  • centos8 yum安装docker 20.10.21 failed to load listeners: no sockets found via so
    vim/usr/lib/systemd/system/docker.serviceExecStart=/usr/bin/dockerd-Hunix://--containerd=/run/containerd/containerd.sock#ExecStart=/usr/bin/dockerd-Hfd......
  • mmap_sew延迟问题
    最近项目上遇到一个延迟问题。问题的现象如下:  程序运行在arm上,linux版本是Linuxversion5.10.35-dirty(root@Newu)(aarch64-linux-gnu-gcc(Ubuntu9.4.0-1ubuntu......
  • 学习笔记-Frida构造数组,对象,Map和类参数
    Frida构造数组,对象,Map和类参数数组/(字符串)对象数组/gson/Java.array对象/多态,强转Java.cast接口interface,Java.register枚举,泛型,List,Map,Set,迭代打印重要思路:开......