• Collection,Map与String互相转换


    工具类

    
    /**
     * 集合工具类
     */
    public class CollectionUtil {
    
    	public static <E> boolean isNotEmpty(Collection<E> collection){
    		return collection != null && !collection.isEmpty();
    	}
    
    	public static <E> boolean isEmpty(Collection<E> collection) {
    		return !isNotEmpty(collection);
    	}
    
    	/**
    	 * 集合 to 字符串
    	 * @param sep 分隔符
    	 */
    	public static <T> String listToString(Collection<T> list, String sep, Function<T, String> function) {
    		if (CollectionUtil.isEmpty(list)) return "";
    		StringBuilder builder = new StringBuilder();
    		for (T t : list) {
    			builder.append(sep);
    			builder.append(function.apply(t));
    		}
    		builder.deleteCharAt(0);
    		return builder.toString();
    	}
    
    	/**
    	 * 字符串 to 集合
    	 * @param sep 分隔符
    	 */
    	public static <R> List<R> stringToList(String str, String sep, Function<String, R> function) {
    		if (!StringUtils.hasLength(str)) return Collections.emptyList();
    		String[] split = str.split(sep);
    		List<R> result = new ArrayList<>(split.length);
    		for (String s : split) {
    			result.add(function.apply(s));
    		}
    		return result;
    	}
    
    	/**
    	 * map to 字符串
    	 *
    	 */
    	public static <K, V> String mapToString(Map<K, V> map, String sep, BiFunction<K, V, String> biFunction) {
    		if (map == null || map.size() == 0) return "";
    		StringBuilder builder = new StringBuilder();
    		map.forEach((k, v) -> {
    			builder.append(sep);
    			builder.append(biFunction.apply(k, v));
    		});
    		builder.deleteCharAt(0);
    		return builder.toString();
    	}
    
    	/**
    	 * 字符串 to map
    	 */
    	public static <K, V> Map<K, V> stringToMap(String str, String sep, Function<String, K> key, Function<String, V> value) {
    		if (!StringUtils.hasLength(str)) return Collections.emptyMap();
    		String[] split = str.split(sep);
    		Map<K, V> map = new HashMap<>(split.length * 4 / 3 + 1);
    		for (String s : split) {
    			map.put(key.apply(s), value.apply(s));
    		}
    		return map;
    	}
    	/**
    	 * 字符串 to map
    	 */
    	public static <K, V, R> Map<K, V> stringToMap(String str, String sep, Function<String, R> handler, Function<R, K> key, Function<R, V> value) {
    		if (!StringUtils.hasLength(str)) return Collections.emptyMap();
    		String[] split = str.split(sep);
    		Map<K, V> map = new HashMap<>(split.length * 4 / 3 + 1);
    		for (String s : split) {
    			R r = handler.apply(s);
    			map.put(key.apply(r), value.apply(r));
    		}
    		return map;
    	}
    
    	/**
    	 * 从集合中查找某个元素
    	 */
    	public static <T, F> T find(Collection<T> collection, Predicate<T> predicate) {
    		if (isEmpty(collection)) return null;
    		for (T t : collection) {
    			if (predicate.test(t)) {
    				return t;
    			}
    		}
    		return null;
    	}
    
    	/**
    	 * 集合转换
    	 */
    	public static <T, R> List<R> transform(List<T> list, Function<T, R> function) {
    		if (list == null || list.size() == 0) {
    			return Collections.emptyList();
    		}
    		List<R> result = new ArrayList<>(list.size());
    		for (T t : list) {
    			result.add(function.apply(t));
    		}
    		return result;
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111

    单元测试

    public class CollectionUtilTest {
    
        public static List<Student> students;
        public static Map<Integer, Student> studentMap;
        static {
            Student s1 = new Student(1, "c", 3);
            Student s2 = new Student(2, "d", 2);
            Student s3 = new Student(3, "a", 4);
            Student s4 = new Student(4, "b", 1);
            Student s5 = new Student(5, "a", 1);
            students = Arrays.asList(s1, s2, s3, s4, s5);
    
            studentMap = new HashMap<>(students.size());
            studentMap.put(s1.getNo(), s1);
            studentMap.put(s2.getNo(), s2);
            studentMap.put(s3.getNo(), s3);
            studentMap.put(s4.getNo(), s4);
            studentMap.put(s5.getNo(), s5);
        }
    
        @Test
        void listTest() {
            // 简单类型 list to string
            List<String> strings = Arrays.asList("a", "b", "c");
            String join = StringUtils.collectionToDelimitedString(strings, ",");
            System.out.println("join = " + join);
    
            // string to list
            List<String> list = Arrays.asList(join.split(","));
            System.out.println("list = " + list);
    
            // 排序
            students.sort(Comparator.comparing(Student::getAge).thenComparing(Student::getName));
            System.out.println("students = " + students);
    
            // 比较
            Comparator<Student> comparator = (student1, student2) -> student1.age - student2.getAge();
            System.out.println("age min = " + Collections.min(students, comparator));
            System.out.println("age max = " + Collections.max(students, comparator));
    
            // 转换
            List<Integer> transform = CollectionUtil.transform(students, Student::getAge);
            System.out.println("transform = " + transform);
    
            // to string
            String listToString = CollectionUtil.listToString(students, ",", student -> student.getNo() + "_" + student.getName());
            System.out.println("listToString = " + listToString);
    
            // to list
            List<Student> students1 = CollectionUtil.stringToList(listToString, ",", s -> {
                String[] split = s.split("_");
                return new Student(Integer.parseInt(split[0]), split[1], 0);
            });
            System.out.println("students1 = " + students1);
    
            // find
            Student find = CollectionUtil.find(students, student -> student.getAge() == 4);
            System.out.println("find = " + find);
        }
    
        @Test
        void mapTest() {
            // map to string
            String toString = CollectionUtil.mapToString(studentMap, ",", (no, student) -> no + "_" + student.getName() + "_" + student.getAge());
            System.out.println("toString = " + toString);
    
            // 1 string to map
            Map<String, Student> map = CollectionUtil.stringToMap(toString, ",", s -> s.split("_")[0], s -> {
                String[] split = s.split("_");
                return new Student(Integer.parseInt(split[0]), split[1], Integer.parseInt(split[2]));
            });
            System.out.println("map = " + map);
    
            // 2 string to map
            Map<String, Student> map2 = CollectionUtil.stringToMap(toString, ",",
                    s -> s.split("_"),
                    array -> array[0],
                    array -> new Student(Integer.parseInt(array[0]), array[1], Integer.parseInt(array[2])));
            System.out.println("map2= " + map2);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81

    pojo 类

    @Data
    public class Student {
    	public int no;
    	public String name;
    	public int age;
    
    	public Student(int no, String name, int age) {
    		this.no = no;
    		this.name = name;
    		this.age = age;
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
  • 相关阅读:
    学习Java的第六天
    电机控制从入门到吹牛
    【Harmony OS】【ArkUI】ets开发 创建视图与构建布局
    【Azure 事件中心】Event Hub 无法连接,出现 Did not observe any item or terminal signal within 60000ms in 'flatMapMany' 的错误消息
    Java Story
    力扣第312场周赛题解:
    浅谈大数据背景下用户侧用电数据在电力系统的应用与发展分析
    数据仓库与数据挖掘实验练习3-4(实验二2024.5.8)
    java计算机毕业设计小小银动漫网站源码+系统+数据库+lw文档+mybatis+运行部署
    CVPR 2022 | 网络中批处理归一化估计偏移的深入研究
  • 原文地址:https://blog.csdn.net/qiuwen_521/article/details/126163691