Bootstrap

集合练习题

集合练习题

1、产生 10 个 1-100 的随机数,并放到一个数组中,把数组中大于等于 10 的数字放到一个 list 集合中,并打印到控制台

public class Test01 {
   
	public static void main(String[] args) {
   
		Random r = new Random();
		List<Integer> list = new ArrayList<>();
		int[] arr = new int[10];
		for (int i = 0; i < arr.length; i++) {
   
			arr[i] = r.nextInt(100) + 1;
			if (arr[i] > 10)
				list.add(arr[i]);
		}
		for (int i : list) {
   
			System.out.println(i);
		}
	}
}

2、假设顺序列表 ArrayList 中存储的元素是整型数字 1~5,请使用你所知的所有方法遍历每个 元素,将每个元素顺序输出

public class Test02 {
   
	public static void main(String[] args) {
   
		List<Integer> list = new ArrayList<>();
		for (int i = 1; i <= 5; i++) {
   
			list.add(i);
		}
		// 方法1
		list.forEach(System.out::println);
		// 方法2
		Iterator<Integer> it = list.iterator();
		while (it.hasNext()) {
   
			Integer next = it.next();
			System.out.println(next);
		}
		// 方法3
		for (int i = 0; i < list.size(); i++) {
   
			System.out.println(list.get(i));
		}
	}
}

3、从控制台输入若干行英文内容(输入回车一行结束,输入 quit 表示输入完成)以单词的方 式放入集合中,将这些单词忽略大小写按照出现次数自然排序,如果次数相等,则按照字母 顺序倒序后打印出来

public class Test03 {
   
	public static void main(String[] args) throws Exception {
   
		try (BufferedReader br = new BufferedReader(new InputStreamReader(System.in))) {
   
			List<WordNum> list = new ArrayList<WordNum>();
			while (true) {
   
				String ss = br.readLine();
				if ("quit".equalsIgnoreCase(ss))
					break;
				String[] arr = ss.toLowerCase().split(" ");
				for (String temp : arr) {
   
					if (temp != null && temp.trim().length() > 0) {
   
						WordNum wn = new WordNum(temp);
						int pos = list.indexOf(wn);
						if (pos != -1) {
   
							wn = list.get(pos);
							wn.addNum();
						} else {
   
							list.add(wn);
						}
					}
				}
			}
			Collections.sort(list, (obj1, obj2) -> {
   
				int res = 0;
				if (obj1 != null && obj2 != null) {
   
					res = obj1.getNum() - obj2.getNum();
					if (res == 0) {
   
						res = obj2.getWord().compareTo(obj1.getWord());
					}
				}
				return res;
			});
			list.forEach(System.out::println);
		}
	}
}

class WordNum {
   
	private String word;
	private int num = 1;

	public WordNum(String word) {
   
		this.word = word;
	}

	public void addNum() {
   
		this.num++;
	}

	public int getNum() {
   
		return num;
	}

	public String getWord() {
   
		return word;
	}

	@Override
	public String toString() {
   
		return "WordNum [word=" + word + ", num=" + num + "]";
	}

	@Override
	public int hashCode() {
   
		final int prime = 31;
		int result = 1;
		result = prime * result + ((word == null) ? 0 : word.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;
		WordNum other = (WordNum) obj;
		if (word == null) {
   
			if (other.word != null)
				return false;
		} else if 
;