SortedSet_TreeSet顺序集合的遍历

SortedSet_TreeSet顺序集合的遍历

代码如下

package com.qbsea.arithmetic.setz;

public class CatModel {
	private String name;
	private Integer age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	
}
package com.qbsea.arithmetic.setz;

import java.util.Comparator;
import java.util.Random;
import java.util.SortedSet;
import java.util.TreeSet;


public class SortedSetTest {
	public static void main(String[] args) {
		SortedSet<CatModel> sortedSet = new TreeSet<>(Comparator.comparing(CatModel::getAge));
		SortedSet<CatModel> sortedSet = new TreeSet<>(new Comparator<CatModel>() {
			@Override
			public int compare(CatModel o1, CatModel o2) {
				if(o1!=null&&o2!=null) {
					if(o1.getAge()<o2.getAge()) {
						return -1;  //前一个小于后一个 -1 为递增  1,2,3,4
					}else {
						return 1;
					}
				}
				return 0;
			}
		});
		Random random = new Random();
		for(int i=0;i<5;i++) {
			CatModel cat = new CatModel();
			cat.setAge(random.nextInt(80));
			cat.setName("name"+i);
			sortedSet.add(cat);
		}
		sortedSet.forEach(record ->{
			System.out.println(record.getAge()+" name="+record.getName());
		});
	}
}

猜你喜欢

转载自blog.csdn.net/maqingbin8888/article/details/82998358