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

com.godmonth.util.collections.List2MapFactoryBean Maven / Gradle / Ivy

package com.godmonth.util.collections;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import com.google.common.base.Function;
import com.google.common.collect.Maps;

import jodd.bean.BeanUtil;

public class List2MapFactoryBean implements FactoryBean>, InitializingBean {
	private List sourceList;
	private String propertyPath;
	protected Map map;

	@Override
	public void afterPropertiesSet() throws Exception {
		map = list2Map(sourceList, propertyPath);
	}

	public static  Map list2Map(List sourceList, final String propertyName) {
		Function function = new Function() {

			@SuppressWarnings("unchecked")
			@Override
			public KEY apply(VALUE input) {
				return (KEY) BeanUtil.silent.getProperty(input, propertyName);
			}

		};
		if (CollectionUtils.isNotEmpty(sourceList)) {
			Map map = Maps.uniqueIndex(sourceList, function);
			return map;
		} else {
			return new HashMap();
		}
	}

	public void setSourceList(List sourceList) {
		this.sourceList = sourceList;
	}

	@Override
	public Map getObject() throws Exception {
		return map;
	}

	@Override
	public Class getObjectType() {
		return Map.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}

	public void setPropertyPath(String propertyPath) {
		this.propertyPath = propertyPath;
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy