201521123083《Java程序设计》第8周学习总结

1. 本周学习总结

这周因为一些事情耽搁了,几乎没什么打java代码,这几天尽量补过来

2. 书面作业

1.List中指定元素的删除

1.1 实验总结

不贴大段代码了,简要总结一下。切割成数组,主要用的是String自带的spilit函数,传进去的是
正则表达式。我用的是\s+。其中s是空格,+是一个或多个(区别于.)。最前面的是因为后面的具有特殊意义。然后删除元素,我是foreach删除,抛出Exception in thread "main" java.util.ConcurrentModificationException。最后迭代删除

2.统计文字中的单词数量并按出现次数排序(尽量不要出现代码)

这题就是map按照value进行排序的题目。如果是按照key进行排序,还比较块,value排序的思路是先将map中的key-value放入list,然后用Collections.sort对list排序,再将排序后的list放入LinkedHashMap,最后返回LinkedHashMap。

3.倒排索引(题目5-4)

这题就是把本来key是Integer,value是String类型的List的字典转化为key是String,value
是Integer类型的List的字典。

4.Stream与Lambda

4.1 使用传统方法编写一个方法,将id>10,name为zhang, age>20, gender为女,参加过ACM比赛的学生筛选出来,放入新的集合。在main中调用,然后输出结果。

public boolean isJoinACM(Student stu) {
	if(stu.id>10&stu.name.equals("zhang")&stu.age>20&stu.gender.equals("Man")){
		return true;
	}
	return false;
}
public List<Student> toCollecions(List<Student> lists){
	List<Student> temp=new ArrayList<Student>();
	for (Student student : lists) {
		if(isJoinACM(student)){
			temp.add(student);
		}
	}
	return temp;
	
}

4.2 使用java8中的stream(), filter(), collect()编写功能同4.1的函数,并测试。

public List<Student> toCollecions(List<Student> lists){
		return lists.stream().filter(stu ->
		(stu.id>10&&stu.name.equals("zhang")&&stu.age>20&&stu.gender.equals("Man"))
		).collect(Collectors.toList());
				
		
	}

4.3 构建测试集合的时候,除了正常的Student对象,再往集合中添加一些null,然后重新改写4.2,使其不出现异常。

那就把null给过滤掉

public List<Student> toCollecions(List<Student> lists){
		return lists.stream().filter( stu->stu!=null ).filter(stu ->
		(stu.id>10&&stu.name.equals("zhang")&&stu.age>20&&stu.gender.equals("Man"))
		).collect(Collectors.toList());
				
		
	}

5.泛型类:GeneralStack(题目5-5)

5.1 GeneralStack接口的代码

interface GeneralStack<T>
{
    T push(T item);
    T pop();
    T peek();
    public boolean empty();
    public int size();
}

5.2 结合本题,说明泛型有什么好处

可以让栈可以储存不同类型的元素。相对于不使用泛型直接用object有个好处,就是可以在编译的时候出现会报错,而Object那种有时候强转会出错,但是编译时候却不会报错。

5.3 截图你的提交结果(出现学号)

6.泛型方法

6.1 编写方法max,该方法可以返回List中所有元素的最大值。List中的元素必须实现Comparable接口。编写的max方法需使得String max = max(strList)可以运行成功,其中strList为List类型。

   public static <T extends Comparable<T>> T  max( List<T>  list){
	    T max = list.get(0);
	    for(T i : list){
	        if(i.compareTo(max) > 0)
	            max = i;
	    }
	    return max ;
	}

3. 码云上代码提交记录

原文地址:https://www.cnblogs.com/daikersec/p/6715528.html