如何将List集合转换成Map集合--双层for循环优化问题

当使用for循环遍历二维数组或者双层for循环遍历list集合时,时间复杂度时:n²。
例如:我们要寻找编号相同的学生

for(ListType:item1:list1)
	for(ListType:item2:list2)
		{...}

这种情况我们可以把其中的一个list集合转行成Map集合(JDK8以后提供了lambda表达式),进而减小时间复杂度:
转换方法:

/*为了体现List在转换成Map时的键值冲突的解决方法,此例特意设定两个编号相同的学生*/
	List<Student> list1 = new ArrayList<Student>();
		//使用内部类创建对象
		Student student1 = new DoubleFor().new Student();
		Student student2 = new DoubleFor().new Student();
		Student student3 = new DoubleFor().new Student();
		Student student4 = new DoubleFor().new Student();
		
		student1.setStudentID(1);
		student2.setStudentID(2);
		student3.setStudentID(3);
		student4.setStudentID(3);
		
		student1.setStudentName("张开");
		student2.setStudentName("李鹏");
		student3.setStudentName("原叶");
		student4.setStudentName("华英");
		
		list1.add(student1);
		list1.add(student2);
		list1.add(student3);
		list1.add(student4);
		Map<Integer,Student> map = list1.stream().collect(Collectors.toMap(Student::getStudentID, Function.identity(),(key1,key2)->key2));
		for(int i=1;i<=map.size();i++){
			System.out.println(map.get(i));
			/*
			*从输出结果可以发现,第三个集合元素被覆盖。
			*因为(k1,k2)->k2)的意思是 当k1和k2重复时,map中存入k2对应的键值对。
			*/
		}

toMap中的三个参数的意义:
1.Student::getStudentID;表示以Student的id号作为map集合的key值,所以map中的key的值我们定义为Integer,key也可以用其他生成策略,比如一List集合数据本身作为key值:key->key(lambda表达式);他和Function.identity(),该方法的源码为:

static Function<T, T> identity() {
return t -> t;
}
可以看出,他返回的也是一个(lambda表达式,我自己理解lambda其实和匿名内部类一样,k->k大概就像(随便写个,重在理解):
new currentInter{
currentObject(currentClass k){
return k;
}
}
)意思是一样的,Function.identity()的意思就是返回List1中的元素内容。
如此一来:双层for循环变成了单层for循环:(如要查找编号相同的学生)
for(Student item : List2 )
map.get(item.getStudentID())
{…}

注:本人学生一枚,理解有误的地方法,希望路过大神指教!!!

发布了14 篇原创文章 · 获赞 0 · 访问量 638

猜你喜欢

转载自blog.csdn.net/goodgoodstudyddp/article/details/101059087