All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.anwen.mongo.convert.Converter Maven / Gradle / Ivy

There is a newer version: 2.1.6.1
Show newest version
package com.anwen.mongo.convert;

import com.anwen.mongo.cache.global.PropertyCache;
import com.anwen.mongo.toolkit.InstantUtil;
import com.anwen.mongo.toolkit.StringUtils;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCursor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.stream.Collectors;

public class Converter {

    private static final Logger logger = LoggerFactory.getLogger(Converter.class);

    /**
     * 将FindIterable转换为List>。
     *
     * @param iterable 待转换的FindIterable对象
     * @return java.util.List> 转换后的List>对象
     * @author JiaChaoYang
     * @date 2023/6/29/029
     */
    public static List> convertDocumentToMap(FindIterable iterable) {
        List> resultList = new ArrayList<>();
        try (MongoCursor cursor = iterable.iterator()) {
            while (cursor.hasNext()) {
                resultList.add(convertKeysToCamelCase(cursor.next()));
            }
        }
        return resultList;
    }

    public static Map convertDocumentToMapOne(FindIterable iterable){
        try (MongoCursor cursor = iterable.iterator()) {
            if (cursor.hasNext()) {
                return convertKeysToCamelCase(cursor.next());
            } else {
                return new HashMap<>();
            }
        }
    }

    public static List> convertDocumentToMap(MongoCursor cursor) {
        List> resultList = new ArrayList<>();
        while (cursor.hasNext()) {
            resultList.add(convertKeysToCamelCase(cursor.next()));
        }
        return resultList;
    }

    public static List> convertDocumentToMap(FindIterable iterable, Integer total) {
        List> resultList = new ArrayList<>(total);
        for (Map map : iterable.batchSize(total)) {
            resultList.add(convertKeysToCamelCase(map));
        }
        return resultList;
    }

    public static Map convertKeysToCamelCase(Map map) {
        return map.entrySet().stream()
                .collect(Collectors.toMap(
                        entry -> convertToCamelCaseIfNeeded(entry.getKey()),
                        entry -> convertValue(entry.getValue())
                ));
    }

    private static String convertToCamelCaseIfNeeded(String key) {
        return PropertyCache.mapUnderscoreToCamelCase ? StringUtils.convertToCamelCase(key) : key;
    }

    private static Object convertValue(Object value) {
        if (value instanceof Date) {
            return InstantUtil.convertTimestampToLocalDateTime8(((Date) value).toInstant());
        }
        return value;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy