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 new LinkedHashMap<>(4);
		String[] split = str.split(sep);
		Map<K, V> map = new LinkedHashMap<>(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 new LinkedHashMap<>(4);
		String[] split = str.split(sep);
		Map<K, V> map = new LinkedHashMap<>(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;
	}
}

单元测试

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);
    }
}

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;
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值