Java 寫類C# Lamda表達式

用過C#的人都知道lamda表達式作用於集合的power!簡潔、易用、可讀性強。比如從一個集合中取出所有符合某一條件的所有項:

var fields = skuField.GetFieldList();
<pre name="code" class="csharp">//取出屬性集合中類型爲單選類型且屬性ID字符串含有“_20549_29148”  的所有屬性項
var sizeFields = fields.FindAll(f => f.Type == FieldTypeEnum.SINGLECHECK && f.Id.Contains("_20549_29148"));

現在如何在java 低版本中如何實現類似功能?

可能是這樣:

	<span style="white-space:pre">	</span>List<Field> fields = skuField.getFieldList();
		List<Field> sizeFields = new ArrayList<Field>();
		for (Field f : fields) {
			if (f.getType() == FieldTypeEnum.SINGLECHECK && f.getId().contains("_20549_29148")) {// 歐碼
				sizeFields.add(f);
			}
		}
如果不想總這麼寫循環,有沒有更“優雅”點的方式呢?類C#中的Lamda表達式。

一、從集合中取出符合條件的項:

    1、我們可以創建條件接口IMatch,如下

/**
 * @author zhaojiwei YGCollectionInterface 2015年4月16日
 * @param <T>
 */
public interface IMatch<T> {
	 boolean match(T t);
}
再創建一個集合幫助類YGCollectionHelper,專門實現一些方法,比如find,findAll等

/**
 * @author zhaojiwei YGCollectionHelper 2015年4月16日
 */
public class YGCollectionHelper {
public static <T> T find(Collection<T> list, IMatch<T> collectionInterface) {
		if (CollectionUtils.isEmpty(list)) { return null; }

		for (T t : list) {
			if (collectionInterface.match(t)) { return t; }
		}
		return null;
	}

	public static <T> List<T> findAll(Collection<T> list, IMatch<T> collectionInterface) {
		if (CollectionUtils.isEmpty(list)) { return null; }

		List<T> ts = new ArrayList<T>();
		for (T t : list) {
			if (t != null && collectionInterface.match(t)) {
				ts.add(t);
			}
		}
		return ts;
	}
}
我們該如何使用該集合輔助類呢?很簡單,如下代碼:
@Test
	public void testYGCollection() {
		List<Brand> brands = commodityBaseApiService.getAllBrands();
		Brand brand = YGCollectionHelper.find(brands, new IMatch<Brand>() {

			@Override
			public boolean match(Brand b) {
				return b.getBrandName().equals("耐克"); //boolean表達式:選出品牌名稱爲耐克的品牌項
			}
		});

		if (brand != null) {
			System.out.println(brand.getBrandDesc());
		}

		List<Brand> list1 = YGCollectionHelper.findAll(brands, new IMatch<Brand>() {

			@Override
			public boolean match(Brand t) {
				return t.getDelFlag().equals(1); //選出集合中未刪除的項
			}

		});
		if (list1 != null) {
			System.out.println(list1.size());
		}

		List<String> brandNames = YGCollectionHelper.select(brands, new ISingleMapping<Brand, String>() {

			@Override
			public String func(Brand t) {
				if (t == null || StringUtils.isBlank(t.getBrandName())) { return null; }
				return t.getBrandName();
			}

		});
		if (CollectionUtils.isNotEmpty(brandNames)) {
			for (String brandName : brandNames) {
				System.out.println(brandName);
			}
		}
	}
二、將一個集合中的元素映射爲另一個元素集合(功能類似C# select、selectMany方法)

/**
 * @author zhaojiwei
 * IYGCollectionMapping
 * 2015年4月16日
 */
public interface ISingleMapping<T,E> {
     E func(T t);
}

多元素同時映射:
/**
 * @author zhaojiwei IManyMapping 2015年4月16日
 */
public interface IManyMapping<T, E> {

	Collection<E> selectMany(T t);
}


在集合輔助類中加入方法:select,selectMany:

public static <T, E> List<E> select(Collection<T> list, ISingleMapping<T, E> singleMappingInterface) {
		if (CollectionUtils.isEmpty(list)) { return null; }
		List<E> result = new ArrayList<E>();
		for (T t : list) {
			E e = singleMappingInterface.func(t);
			if (e != null) {
				result.add(e);
			}
		}
		return result;
	}

	public static <T, E> List<E> selectMany(Collection<T> list, IManyMapping<T, E> manyMapping) {
		if (CollectionUtils.isEmpty(list)) { return null; }

		List<E> result = new ArrayList<E>();
		Collection<E> e = null;
		for (T t : list) {
			e = manyMapping.selectMany(t);
			if (e != null) {
				result.addAll(e);
			}
		}
		return result;
	}

如何使用?

List<String> brandNames = YGCollectionHelper.select(brands, new ISingleMapping<Brand, String>() {

			@Override
			public String func(Brand t) {
				if (t == null || StringUtils.isBlank(t.getBrandName())) { return null; }
				return t.getBrandName();
			}

		});
		if (CollectionUtils.isNotEmpty(brandNames)) {
			for (String brandName : brandNames) {
				System.out.println(brandName);
			}
		}

三、其它功能點的實現

/**
 * @Date:2015年4月16日
 * @Author: zhaojiwei
 * @Description:
 */
package com.yougou.gms.utils.ygcollection;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.alibaba.dubbo.common.utils.CollectionUtils;

/**
 * @author zhaojiwei YGCollectionHelper 2015年4月16日
 */
public class YGCollectionHelper {

	public static <T> T first(Collection<T> list) {
		if (CollectionUtils.isEmpty(list)) return null;
		int i = 0;
		for (T t : list) {
			if (i++ == 0) { return t; }
		}
		return null;
	}

	public static <T> boolean exists(Collection<T> list, IMatch<T> collectionInterface) {
		if (CollectionUtils.isEmpty(list)) { return false; }

		for (T t : list) {
			if (collectionInterface.match(t)) { return true; }
		}
		return false;
	}

	public static <T> boolean all(Collection<T> list, IMatch<T> collectionInterface) {
		if (CollectionUtils.isEmpty(list)) { return false; }

		for (T t : list) {
			if (!collectionInterface.match(t)) { return false; }
		}
		return true;
	}

	public static <T> boolean any(Collection<T> list, IMatch<T> collectionInterface) {
		return exists(list, collectionInterface);
	}

	public static <T> T find(Collection<T> list, IMatch<T> collectionInterface) {
		if (CollectionUtils.isEmpty(list)) { return null; }

		for (T t : list) {
			if (collectionInterface.match(t)) { return t; }
		}
		return null;
	}

	public static <T> List<T> findAll(Collection<T> list, IMatch<T> collectionInterface) {
		if (CollectionUtils.isEmpty(list)) { return null; }

		List<T> ts = new ArrayList<T>();
		for (T t : list) {
			if (t != null && collectionInterface.match(t)) {
				ts.add(t);
			}
		}
		return ts;
	}

	public static <T, E> List<E> select(Collection<T> list, ISingleMapping<T, E> singleMappingInterface) {
		if (CollectionUtils.isEmpty(list)) { return null; }
		List<E> result = new ArrayList<E>();
		for (T t : list) {
			E e = singleMappingInterface.func(t);
			if (e != null) {
				result.add(e);
			}
		}
		return result;
	}

	public static <T, E> List<E> selectMany(Collection<T> list, IManyMapping<T, E> manyMapping) {
		if (CollectionUtils.isEmpty(list)) { return null; }

		List<E> result = new ArrayList<E>();
		Collection<E> e = null;
		for (T t : list) {
			e = manyMapping.selectMany(t);
			if (e != null) {
				result.addAll(e);
			}
		}
		return result;
	}
}

在使用方法輔助類時,獲取集合或作集合映射時,我們的重點或者說關注點集中在 條件表達式上,不用在反覆滴寫foreach循環遍歷了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章