Groovy 集合类常用api之List篇
参考资料:
<<Programming Groovy>>
DefaultGroovyMethods源代码
Groovy collection 常用api之List篇:
1 each
each 源代码<私有方法>:
private static <T> Iterator<T> each(Iterator<T> iter, Closure closure) {
while (iter.hasNext()) {
closure.call(iter.next()); // 在闭包中改变it这个默认参数是达不到更改集合的效果的.
}
return iter;
}
each 将集合中的每一个元素传递到闭包中执行,也就是闭包直接修改元素,并且是执行一个iterator,注意多线程同时修改引发的异常. 最终将处理完毕的List
返回,注意,在闭包中使用 it = "changedValue"是不会有效的! 例如:
def list = ["1",2,3,54]
list.each{
if(it.equals("1")){
//try to change the value,but it is noe affect the list!!
it = "changed"
}
}
assert list == ["1",2,3,54]
如果想要得到闭包修改以后的集合,使用方法: collect
2 collect: 使得每一个集合元素都参与闭包的运算,并最终返回一个新的集合,此集合的每一个元素都是闭包执行后的结果.
源代码:<私有方法>
public static Collection collect(Collection self, Collection collection, Closure closure) {
for (Iterator iter = self.iterator(); iter.hasNext();) {
collection.add(closure.call(iter.next()));
if (closure.getDirective() == Closure.DONE) {
break;
}
}
return collection;
}
测试:
def list = [1,2,3,4]
assert list.collect {
it * 2;
} == [2,4,6,8]
//原来的集合不变
assert list == [1,2,3,4]
3 find方法以及findAll方法: 注意,find方法只查找第一个
源代码: public static Object find(Object self, Closure closure) { for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) { Object value = iter.next(); if (DefaultTypeTransformation.castToBoolean(closure.call(value))) { //如果满足条件 return value; //只是返回第一个 } } return null; //不满足闭包调价就返回null } 测试代码: def list = [1,2,3,4] assert 1 == list.find { it < 5 //表明闭包会返回一个boolean } //原来的集合不变 assert list == [1,2,3,4] ====================findAll <源代码> private static <T> Collection<T> findAll(Closure closure, Collection<T> answer, Iterator<T> iter) { while (iter.hasNext()) { T value = iter.next(); if (DefaultTypeTransformation.castToBoolean(closure.call(value))) { answer.add(value); //把符合闭包条件的元素添加到新的集合answer中. } } return answer; }
4 inject 方法: 每次都会传入value和每一个集合元素给闭包,并返回闭包的执行结果,注意,闭包对应的参数是一个object[2],要有两个参数
public static Object inject(Iterator self, Object value, Closure closure) { Object[] params = new Object[2]; while (self.hasNext()) { Object item = self.next(); params[0] = value; params[1] = item; value = closure.call(params); } return value; } 测试代码: def list = [1,2,3,4] assert list.inject(1) { param1, param2 -> param1 + param2; } == 11 //(1+1,2+2,4+3,7+4),最终为11
5 一些辅助的集合方法:
5.1 sum()方法:
def list = [1,2,3,4]
assert list.sum() == 10
//代闭包的sum方法;
assert list.sum{
it * 2
} == 20
5.2 join()方法: 将集合合并
def list = [1,2,3,4]
assert list.join().class == String
assert list.join() == "1234"
//带上分隔符
assert list.join('|') == "1|2|3|4"
5.3 flatten方法:
先将测试代码贴出;
def list1 = [["Be" , "Productive" ], "In" , "Groovy" ];
assert list1.flatten() == ["Be" , "Productive" , "In" , "Groovy" ]
源代码贴出:
DefaultGroovyMethods类中的代码:
private static Collection flatten(Collection elements, Collection addTo) {
for (Object element : elements) {
if (element instanceof Collection) {
flatten((Collection) element, addTo);
} else if (element != null && element.getClass().isArray()) {
flatten(DefaultTypeTransformation.arrayAsCollection(element), addTo);
} else {
// found a leaf
addTo.add(element);
}
}
return addTo;
}
DefaultGroovyMethodsSuport中的代码贴出:[这里只是贴出有关List的,map,set的请参考相关源代码]
protected static <T> List<T> createSimilarList(List<T> orig, int newCapacity) {
if (orig instanceof LinkedList)
return new LinkedList<T>();
if (orig instanceof Stack)
return new Stack<T>();
if (orig instanceof Vector)
return new Vector<T>();
return new ArrayList<T>(newCapacity);
}
5.4 groupBy方法: public static <T> Map<Object, List<T>> groupBy(Collection<T> self, Closure closure) 方法根据传入的闭包执行以后, 闭包执行的结果被
封装为一个Map Entry的key,集合元素被封装为对应key的value. 源代码如下:
public static <T> Map<Object, List<T>> groupBy(Collection<T> self, Closure closure) { Map<Object, List<T>> answer = new LinkedHashMap<Object, List<T>>(); //创建相关的MAP for (T element : self) { Object value = closure.call(element);//执行闭包,并保存闭包的执行结果到value groupAnswer(answer, element, value); } return answer; } //下面是groupAnser的源代码: protected static <T> void groupAnswer(final Map<Object, List<T>> answer, T element, Object value) { if (answer.containsKey(value)) { answer.get(value).add(element); } else { List<T> groupedElements = new ArrayList<T>(); //如果闭包的执行结果value不存在Map的keySet中, 建立一个新的ArrayList存放对应集合元素 groupedElements.add(element); answer.put(value, groupedElements);//加入Map中. } }
5.5 count函数: 计算传入参数值匹配的个数,相当于在一个集合中统计出现元素的次数. 示例代码:
assert [2,4,2,1,3,5,2,4,3].count(4) == 2
2018年11月12日 12:34
The kind of web portals who providing the basic sample programs and all-time assistance on the languages will help a lot of students. Especially the students who take their paper as Computer applications
2018年11月12日 14:21
Why did you use the functions private on static and collect, no need to set static as private, anyway it's not gonna affect anything as its static? It just creates confusion, no other benefit will be provided.
2018年11月20日 14:54
This blog is helpful for students. here the blogger explains with an example. this faster grasping of program and application of api.
2019年10月05日 17:46
We need to be one of the best housekeeping Service relating to maintaining real estate and companies. We own devised an incomparable work arrange for maids. Home maid training program is mainly completed by way of the maids the fact that choose it all as work.
2021年9月24日 20:00
Attributes carefully pitfalls about hiring free cleaners and additionally hire the best, professional housecleaning service. An established business should run criminal background checks on their cleaners, provide training for a workers, come to be properly guaranteed against affect, theft and additionally breakage, is normally properly to ensure. Having this in space assures of the fact that cleaner this really is servicing your home is a valid professional and really should something get wrong, you, the credit card holder has allowed by the law recourse.
2023年8月23日 17:45
Through studying the actual emerging needs of cleansing services, lots of companies took the route of web. It helps visitors to easily find cleaning businesses, understand the kind of services they provide and consider their assist after learning the monetary aspect. This kind of online cleansing service work also offers an ease towards the locater as well as frees him in the worry associated with contacting the company over and over.