要从一个List集合中,找出Person的id为id1的对象,除了遍历有什么更简便的写法?我记得c#中可以直接find,就一行代码?想让一个List集合中,所有元素的id作为一个数组输出如[id1,id2,id3...],除了遍历有什么简便写法?
2 回答
慕田峪9158850
TA贡献1794条经验 获得超7个赞
可能不太简洁,但是可以自己写:importjava.util.Arrays;importjava.util.Iterator;importjava.util.List;publicfinalclassListUtils{publicstaticTcollectFirst(finalIterable list,finalPredicate predicate){ for(Telement:list){if(predicate.apply(element)){returnelement;}}returnnull;}publicstaticIterablemap(finalIterablelist,finalF1func){returnnewIterable(){@OverridepublicIteratoriterator(){returnnewIterator(){privateIteratori=list.iterator();@OverridepublicbooleanhasNext(){returni.hasNext();}@OverridepublicBnext(){returnfunc.apply(i.next());}@Overridepublicvoidremove(){i.next();}};}};}publicstaticvoidmain(String[]args){finalListintegers=Arrays.asList(1,2,3,4,5,6); finalIntegerresult=collectFirst(integers,newPredicate(){ @Overridepublicbooleanapply(Integere){returne.compareTo(3)>0;}});System.out.println(String.format("Thefirstintegerlargerthan3is%d",result));finalIterableresults=map(integers,newF1 (){ @OverridepublicIntegerapply(Integerinteger){returninteger*integer;}});System.out.println("Thesquaresofthemare:");for(Integeri:results){System.out.print(i+"");}}publicinterfacePredicate{ booleanapply(finalTe);}publicinterfaceF1{Bapply(finalAa);}}
添加回答
举报
0/150
提交
取消