尚學堂-Day016

運氣不可能持續一輩子,能幫助你持續一輩子的東西只有你個人的能力。

  • Collections
  • Comparable
  • Comparator
  • Stream

一、Collections

提供了對容器操作的工具方法,與 Arrays 使用差不多。

1、常用方法

	List<Integer> list = new ArrayList<Integer>();
	list.add(50);
	list.add(33);
	list.add(52);
	list.add(45);
	System.out.println(list);
	
	Collections.sort(list);		// 排序、默認按照升序排序
	System.out.println(list);
	
	System.out.println(Collections.binarySearch(list, 50));	// 二分查找(前提必須是有序的)
	
	Collections.reverse(list);	// 反轉
	System.out.println(list);
	
	Collections.shuffle(list);	// 亂序
	System.out.println(list);
	
	Collections.fill(list, 0);	// 填充,填充爲指定值
	System.out.println(list);
運行結果
[50, 33, 52, 45]
[33, 45, 50, 52]
2
[52, 50, 45, 33]
[33, 45, 52, 50]
[0, 0, 0, 0]

二、Comparable

通過實現Comparable接口進行排序

public 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 int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		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 (age != other.age)
			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 + ", age=" + age + "]";
	}
	@Override
	public int compareTo(Student o) {
		// TODO Auto-generated method stub
		// 0 不變    負數小於 正數大於
		return this.age-o.getAge();
	}
}

public class Test2 {
	public static void main(String[] args) {
		List<Student> list = new ArrayList<Student>();
		list.add(new Student("張三",20));
		list.add(new Student("李四",22));
		list.add(new Student("王二",24));
		list.add(new Student("麻子",19));
		Collections.sort(list);		// 排序
		for(Student s:list) {
			System.out.println(s);
		}
	}
}
運行接口
Student [name=麻子, age=19]
Student [name=張三, age=20]
Student [name=李四, age=22]
Student [name=王二, age=24]

三、Comparator

Comparator比較器,可以根據需要定製特定的比較規則。

public class Test3 {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>();
		list.add(50);
		list.add(33);
		list.add(52);
		list.add(45);
		System.out.println(list);
		// Comparator 內部類排序
		Collections.sort(list, new Comparator<Integer>() {
			@Override
			public int compare(Integer o1, Integer o2) {
				// TODO Auto-generated method stub
				return o1.compareTo(o2);		// 使用Integer提供的比較規則
			}
		});
		System.out.println(list);
		System.out.println("------------");
		Collections.shuffle(list);		// 隨機排序
		System.out.println(list);
		System.out.println("------------");
		Collections.sort(list,(o1,o2)->o1-o2);		// lambda排序
		System.out.println(list);
		System.out.println("------------");
		Collections.sort(list,Test3::a1);
		System.out.println(list);	
	}
	static int a1(int o1,int o2) {
		return -(o1-o2);
	}
}
運行結果
[50, 33, 52, 45]
[33, 45, 50, 52]
------------
[52, 45, 33, 50]
------------
[33, 45, 50, 52]
------------
[52, 50, 45, 33]

四、Stream

1、創建源

public class Test4 {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>();
		list.add(50);
		list.add(33);
		list.add(52);
		list.add(45);
		
		// 方式一
		Stream<Integer> stream1 = list.stream();
		
		// 方式二
		Integer[] ints = {1,2,3,4,5,6,7,8,9};
		Stream<Integer> stream2 = Arrays.stream(ints);
		
		// 方式三
		Stream<Integer> stream3 = Stream.of(1,2,3);
		stream3 =  Stream.of(ints);
	}
}

2、中間操作

2.1、切片和篩選

public class Test5 {
	public static void main(String[] args) {
		List<Student> list = new ArrayList<Student>();
		list.add(new Student("張三",20));
		list.add(new Student("李四",22));
		list.add(new Student("王二",24));
		list.add(new Student("麻子",19));
		list.add(new Student("麻子",19));
		
		// 過濾,年齡大於20的
		list.stream().filter(x->x.getAge()>20).forEach(System.out::println);
		System.out.println("---------");
		// 截取元素,獲取前兩個
		list.stream().limit(2).forEach(System.out::println);
		System.out.println("---------");
		// 跳過元素,敲過前兩個
		list.stream().skip(2).forEach(System.out::println);
		System.out.println("---------");
		// 篩選去重,去掉重複的元素
		list.stream().distinct().forEach(System.out::println);
	}
}
運行結果
Student [name=李四, age=22]
Student [name=王二, age=24]
---------
Student [name=張三, age=20]
Student [name=李四, age=22]
---------
Student [name=王二, age=24]
Student [name=麻子, age=19]
Student [name=麻子, age=19]
---------
Student [name=張三, age=20]
Student [name=李四, age=22]
Student [name=王二, age=24]
Student [name=麻子, age=19]

2.2、排序

public class Test6 {
	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		list.add("aa");
		list.add("cc");
		list.add("bb");
		list.add("dd");
		
		// 自然排序
		list.stream().sorted().forEach(System.out::println);
		System.out.println();
		// 定製排序
		list.stream().sorted((o1,o2)->o1.compareTo(o2)).forEach(System.out::println);;
	}
}
運行結果
aa
bb
cc
dd

aa
bb
cc
dd

3、終止

3.1、查找匹配

public class Test7 {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>();
		list.add(50);
		list.add(33);
		list.add(52);
		list.add(45);
		
		// 是否匹配所有元素
		boolean flag = list.stream().allMatch(x->x>30);
		System.out.println(flag);
		
		// 至少匹配一個元素
		flag = list.stream().anyMatch(x->x>50);
		System.out.println(flag);
		
		// 沒有匹配所有元素
		flag = list.stream().noneMatch(x->x>50);
		System.out.println(flag);
		
		// 返回第一個元素
		Optional<Integer> opt = list.stream().findFirst();
		System.out.println(opt);
		
		// 返回任意一個元素
		opt = list.stream().findAny();
		System.out.println(opt);
		
		// 返回流中的元素
		System.out.println(list.stream().count());
		
		// 返回流中的最大值
		opt = list.stream().max((x,y)->x-y);
		System.out.println(opt);
		
		// 返回流中的阿最小值
		opt= list.stream().min((x,y)->x-y);
		System.out.println(opt);
		
	}
}
運行結果
true
true
false
Optional[50]
Optional[50]
4
Optional[52]
Optional[33]

3.2、收集

public class Test8 {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>();
		list.add(50);
		list.add(33);
		list.add(52);
		list.add(45);
//		list.add(45);
		
		// 返回一個List
		List<Integer> list1 = list.stream().limit(2).collect(Collectors.toList());
		System.out.println(list1);
		
		// 返回Set,去除重複
		Set<Integer> set = list.stream().collect(Collectors.toSet());
		System.out.println(set);
		
		// 返回Map
		Map<Integer,Integer> map = list.stream().collect(Collectors.toMap((x)->{return x;}, (x)->{return x;}));
		System.out.println(map);
	}
}
運行結果
[50, 33]
[33, 50, 52, 45]
{33=33, 50=50, 52=52, 45=45}
public class Test10 {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<Integer>();
		list.add(50);
		list.add(33);
		list.add(52);
		list.add(45);
		
		System.out.println(list.stream().collect(Collectors.counting()));	// 求總數
		System.out.println(list.stream().collect(Collectors.averagingInt(x->x)));	// 求平均值
		System.out.println(list.stream().collect(Collectors.summingInt(x->x)));	// 求總和
		System.out.println(list.stream().collect(Collectors.maxBy((x,y)->Integer.compare(x, y))));	// 求最大值
	}
}
運行結果
4
45.0
180
Optional[52]

Tips:

  • Stream自己不會儲存元素
  • Stream不會改變源對象,相反,會返回一個持有結果的新Stream
  • Stream操作是延遲執行的,也就意味着需要結果的時候纔會執行
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章