Java集合(例题及代码)

1.ArrayList集合

创建Student类,属性:学号 姓名 年龄
通过上面的字符串获取学号,姓名,年龄创建Student类,并将Student类的对象保存到一个ArrayList集合中,
以下完成每个步骤完成需要定义方法:
1.写出3种方式遍历集合中的数据(for;for each;iterator)
2.查询里面有没有叫田七的学生如果存在则打印学生的具体信息(封装成方法,键盘输入姓名)
3.计算所有学生的平均年龄,最大年龄,最小年龄
4.如果存在名字叫张三的将名字改为张兵
5.删除年龄小于20岁 的学生从集合中。

public class Student {
	private int id;
	private String name;
	private int age;

	public Student() {
		super();
	}

	public Student(int id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
	}
}
import java.util.List;

public class Function {

	public static Student find(List list, String str) {
		for (int i = 1; i < list.size(); i++) {
			if (str.equals(((Student) list.get(i)).getName())) {
				return (Student) list.get(i);
			}
		}
		return null;
	}
}
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

public class Test {

	public static void main(String[] args) {
		List<Student> list = new ArrayList<>();
		list.add(new Student(1, "张三", 30));
		list.add(new Student(1, "张4", 18));
		list.add(new Student(1, "张5", 16));
		list.add(new Student(1, "张6", 25));
		list.add(new Student(1, "张7", 26));
		list.add(new Student(1, "张8", 14));
		list.add(new Student(1, "田七", 22));

		// 遍历方式1
		for (int i = 1; i < list.size(); i++) {
		}
		System.out.println(list);
		System.out.println("-------------------------------------------");
		// 遍历方式2
		for (Student s2 : list) {
			System.out.println(s2);
		}
		System.out.println("-------------------------------------------");
		// 遍历方式3
		Iterator<Student> it = list.iterator();
		while (it.hasNext()) {
			Student st = it.next();
			System.out.println(st);
		}
		System.out.println("-------------------------------------------");

		// 2.按姓名查找
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入姓名");
		String thename = sc.next();

		Student s1 = Function.find(list, thename);
		if (s1 != null) {
			System.out.println(s1);
		} else
			System.out.println("没有这个学生");

		// 3.计算平均年龄
		double sum = 0;
		int average = 0;
		for (int i = 1; i < list.size(); i++) {
			sum += (list.get(i).getAge());
			average = (int) (sum / list.size());
		}
		System.out.println("平均年龄:" + average);
		// 计算最大年龄
		double max = 0;
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getAge() > max) {
				max = list.get(i).getAge();
			}
		}
		System.out.println("最大值:" + max);
		// 计算最小年龄
		double min = list.get(0).getAge();
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getAge() < min) {
				min = list.get(i).getAge();
			}
		}
		System.out.println("最小值:" + min);

		// 4.如果存在名字叫张三的将名字改为张兵
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getName().equals("张三")) {
				list.get(i).setName("张兵");
			}
		}

		// 5.删除年龄小于20岁 的学生从集合中
		for (int i = 0; i < list.size(); i++) {
			if (list.get(i).getAge() < 20) {
				list.remove(i);
				i--;
			}
		}
		for (Student student : list) {
			System.out.println(student);
		}
	}
}

2.Set集合(能去重,需重写HashCode方法和equals方法)

HashSet
创建一个Student类,有成员变量name和cardId。如果两个学生对象的姓名和学号一样视为同一个学生,
在HashSet中添加学生对象 并遍历打印学生信息。

public class Student {
	private String name;
	private int cardid;

	public Student() {
		super();
	}

	public Student(String name, int cardid) {
		super();
		this.name = name;
		this.cardid = cardid;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getCardid() {
		return cardid;
	}

	public void setCardid(int cardid) {
		this.cardid = cardid;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + cardid;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (cardid != other.cardid)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "Student [name=" + name + ", cardid=" + cardid + "]";
	}
}
import java.util.HashSet;

public class Test1 {
	public static void main(String[] args) {
		HashSet<Student> set = new HashSet<>();
		set.add(new Student("张三", 1001));
		set.add(new Student("张三", 1001));
		set.add(new Student("李四", 1002));
		set.add(new Student("王五", 1003));
		for (Student s : set) {
			System.out.println(s);
		}
	}
}

3.TreeSet集合实现自然排序,必须要实现Comparable接口(重写compareTo方法)

将学生对象添加到TreeSet集合

import java.util.Set;
import java.util.TreeSet;

public class Treeset {
	public static void main(String[] args) {
		Set<Student> ts = new TreeSet<>();
		ts.add(new Student("张三", 21));
		ts.add(new Student("张4", 22));
		ts.add(new Student("张5", 19));
		ts.add(new Student("张6", 19));
		ts.add(new Student("张7", 20));
		for (Student student : ts) {
			System.out.println(student);
		}
	}
}

class Student implements Comparable<Student> {
	private String name;
	private int age;

	public Student() {
		super();
	}

	public Student(String name, int age) {
		super();
		this.name = name;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Student [name=" + name + ", age=" + age + "]";
	}

	@Override
	public int compareTo(Student other) {
		int i=this.age - other.age;
		if(i==0){
			i=this.name.compareTo(other.name);
		}
		return i;
	}
}

4.TreeSet集合实现定制排序,(1)创建一个比较器Comparetor,抽象方法compare (2)在创建TreeSet时,通过有参构造把比较器对象传进去

键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低输出到控制台

public class Student {
	private String name;
	private double score1;
	private double score2;
	private double score3;
	private double sum = score1 + score2 + score3;

	public Student() {
		super();
	}

	public Student(String name, double sum) {
		super();
		this.name = name;
		this.sum = sum;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getScore1() {
		return score1;
	}

	public void setScore1(double score1) {
		this.score1 = score1;
	}

	public double getScore2() {
		return score2;
	}

	public void setScore2(double score2) {
		this.score2 = score2;
	}

	public double getScore3() {
		return score3;
	}

	public void setScore3(double score3) {
		this.score3 = score3;
	}

	public double getSum() {
		return sum;
	}

	public void setSum(double sum) {
		this.sum = sum;
	}

	@Override
	public String toString() {
		return "Student [name=" + name + ", sum=" + sum + "]";
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		long temp;
		temp = Double.doubleToLongBits(score1);
		result = prime * result + (int) (temp ^ (temp >>> 32));
		temp = Double.doubleToLongBits(score2);
		result = prime * result + (int) (temp ^ (temp >>> 32));
		temp = Double.doubleToLongBits(score3);
		result = prime * result + (int) (temp ^ (temp >>> 32));
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Student other = (Student) obj;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		if (Double.doubleToLongBits(score1) != Double.doubleToLongBits(other.score1))
			return false;
		if (Double.doubleToLongBits(score2) != Double.doubleToLongBits(other.score2))
			return false;
		if (Double.doubleToLongBits(score3) != Double.doubleToLongBits(other.score3))
			return false;
		return true;
	}
}
import java.util.Comparator;
import java.util.Scanner;
import java.util.TreeSet;

public class Test {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		Comparator<Student> com = new Comparator<Student>() {
			@Override
			public int compare(Student o1, Student o2) {
				double i = -(o1.getSum() - o2.getSum());
				if (i == 0) {
					i = o1.getName().compareTo(o2.getName());
				}
				return (int) i;
			}
		};
		TreeSet<Student> set = new TreeSet<>(com);
		for (int i = 1; i < 6; i++) {
			System.out.println("输入第" + i + "个同学姓名");
			String name = sc.next();
			System.out.println("输入第" + i + "个同学语文成绩");
			double score1 = sc.nextDouble();
			System.out.println("输入第" + i + "个同学数学成绩");
			double score2 = sc.nextDouble();
			System.out.println("输入第" + i + "个同学英语成绩");
			double score3 = sc.nextDouble();
			double sum = score1 + score2 + score3;
			set.add(new Student(name, sum));
		}
		for (Student s : set) {
			System.out.println(s);
		}
	}
}

5.Map集合(键值对)

在map集合中存储5个学生对象,用id作为键 学生对象作为值

public class Student {
	private String name;
	private String sex;

	public Student() {
		super();
	}

	private int age;

	public Student(String name, String sex, int age) {
		super();
		this.name = name;
		this.sex = sex;
		this.age = age;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Student [name=" + name + ", sex=" + sex + ", age=" + age + "]";
	}
}
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map.Entry;
import java.util.Set;

public class Test {

	public static void main(String[] args) {
		HashMap<Integer, Set<Student>> map = new HashMap<>();
		LinkedHashSet<Student> set1 = new LinkedHashSet<>();
		LinkedHashSet<Student> set2 = new LinkedHashSet<>();
		LinkedHashSet<Student> set3 = new LinkedHashSet<>();
		set1.add(new Student("张三", "男", 18));
		set2.add(new Student("李四", "女", 18));
		set3.add(new Student("王五", "男", 18));
		map.put(1, set1);
		map.put(2, set2);
		map.put(3, set3);
		Set<Entry<Integer, Set<Student>>> entrySet = map.entrySet();
		for (Entry<Integer, Set<Student>> entry : entrySet) {
			System.out.println(entry.getKey() + "\n" + entry.getValue());
		}
	}
}

你可能感兴趣的:(java基础)