Chapter类
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlValue;
/** * 章 * @author xiaofanku */
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement
public class Chapter implements Serializable{
/** * 章的ID */
@XmlAttribute
@XmlID
private String chapterId;
/** * 显示顺序 */
@XmlAttribute
private int order;
/** * 标题 */
@XmlValue
private String title;
/** * 作者 */
@XmlAttribute
private String author;
//ETC set/get
}
目标:尝试从Collection取符合条件的某一个对象,填充数据
/** * @param args the command line arguments */
public static void main(String[] args) {
// TODO code application logic here
//Lexicon l=new Lexicon();
List<Chapter> csl=new ArrayList<>();
Chapter c1=new Chapter();
c1.setTitle("the 1 title item");
c1.setChapterId("123");
csl.add(c1);
for(int i=10;i<60;i++){
Chapter _tmp=new Chapter();
_tmp.setTitle(StringHelper.randomCharacter(10));
_tmp.setChapterId(i+"");
csl.add(_tmp);
_tmp=null;
}
Chapter c2=new Chapter();
c2.setTitle("the 2 title item");
c2.setChapterId("123456");
csl.add(c2);
for(int i=61;i<151;i++){
Chapter _tmp=new Chapter();
_tmp.setTitle(StringHelper.randomCharacter(11));
_tmp.setChapterId(i+"");
csl.add(_tmp);
_tmp=null;
}
Chapter c3=new Chapter();
c3.setTitle("the 3 title item");
c3.setChapterId("789");
csl.add(c3);
}
使用以下三种方法来完成目标,
A) 原生的增强for
public static Chapter getOneById(List<Chapter> rs,String chapterId){
Chapter c=null;
for(Chapter chap:rs){
if(chap.getChapterId().equalsIgnoreCase(chapterId)){
c=chap;
break;
}
}
return c;
}
B) Apache common collection4
public static Chapter getOneByIdUsedCommonsCollection4(final List<Chapter> rs,final String chapterId){
return CollectionUtils.find(rs, new org.apache.commons.collections4.Predicate<Chapter>(){
@Override
public boolean evaluate(Chapter t) {
return t.getChapterId().equalsIgnoreCase(chapterId);
}
});
}
C) Jdk8的stream流
public static Chapter getOneByIdUsedJdk8(final List<Chapter> rs,final String chapterId){
Optional<Chapter> data=rs.stream().filter(new java.util.function.Predicate<Chapter>(){
@Override
public boolean test(Chapter t) {
return t.getChapterId().equalsIgnoreCase(chapterId);
}
}).findFirst();
return data.get();
}
下面是我的配置
Intel E3 + 16G + 机械硬盘
下面是我的环境
Win10 + JDK8 + NetBeans8.1
下面是测试示例结果
long beginTime = System.nanoTime();
getOneById(csl,"789");//search element uesed Second:0.000207
//getOneByIdUsedCommonsCollection4(csl,"789");//search element uesed Second:0.003840
//getOneByIdUsedJdk8(csl,"789");//search element uesed Second:0.069668
long endTime = System.nanoTime();
System.out.printf("search element uesed Second:%f%n",(endTime-beginTime)/1.0e9);