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));