集合里要掌握的重要接口

1.Iteraror(迭代器)

接口中定义了如下四个方法: (其功能不过多累赘)
boolean hasNext()
Object next()
void remove()
void forEachRemaining(Consumer action) //lambda表达式目标类型是Consumer

//获取books集合的迭代器
var it = books.iterator();
it.forEachRemaining(obj -> System.out.pritnln("迭代元素:" + obj));

2.comparable(自然排序)

该类供供要排序的类(也就是加入集合中的类)继承。
接口中只有一个方法:compareTo​,供要排序的类(也就是加入集合中的类)重写,
compareTo​

import java.util.*;
class Goat implements Comparable<Goat>
{
	private double weight;
	private String color;
	public Goat(String color,double weight)
	{
		this.weight = weight;
		this.color = color;
	}
	@Override
	public String toString()
	{
		return "[weight: " + this.weight + ", color: " + this.color + "]";
	}
	@Override
	public int compareTo(Goat obj)
	{
		return this.weight > obj.weight ? 1 :(
			this.weight < obj.weight ? -1 : 0);
	}
}
public class ComparableTest
{
	public static void main(String[] args)
	{
		Set<Goat> ts = new TreeSet<>();
		ts.add(new Goat("黑色",12.5));
		ts.add(new Goat("白色",150.3));
		ts.add(new Goat("白色",10.8));
		System.out.println(ts);
		
	}
}

3.Comaprator(定制排序)

该类的子类供TreeSet作为参数传入。
该接口是个函数式接口,只有一个抽象方法:compare,所以可以用lambda表达式来重写compare

import java.util.*;
class Goat
{
	private double weight;
	private String color;
	public Goat(String color,double weight)
	{
		this.weight = weight;
		this.color = color;
	}
	public double getWeight()
	{
		return this.weight = weight;
	}
	public String getColor()
	{
		return this.color = color;
	}
	@Override
	public String toString()
	{
		return "[weight: " + this.weight + ", color: " + this.color + "]";
	}
}
public class ComparatorTest
{

	public static void main(String[] args)
	{
		//创建Comparator子类,重写方法compare(),将该子类当做参数传入TreeSet构造器。
		Set<Goat> ts = new TreeSet<>(new Comparator<Goat>()
		{
			@Override
			public int compare(Goat g1,Goat g2)
			{
				return g1.getWeight() > g2.getWeight() ? 1 :(
				g1.getWeight() < g2.getWeight() ? -1 : 0);/			}
		});
		ts.add(new Goat("黑色",12.5));
		ts.add(new Goat("白色",150.3));
		ts.add(new Goat("白色",10.8));
		ts.add(new Goat("绿色",10.8));
		System.out.println(ts);
	}
}

上面创建ts部分用lambda表达式写法为

		Set<Goat> ts = new TreeSet<>((g1,g2) ->
			 g1.getWeight() > g2.getWeight() ? 1 :(
			g1.getWeight() < g2.getWeight() ? -1 : 0));

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值