TreeMap与Iterator
- TreeSet或TreeMap里面定义的是引用类型的话,就必须实现Comparable接口
import java.util.*;
public class a {
public static void main(String[] args) {
Map<Integer, String> treemap = new TreeMap();
treemap.put(1, "aa");
treemap.put(2, "bb");
treemap.put(3, "cc");
for (Integer key : treemap.keySet()) {
System.out.println(key + "-----" + treemap.get(key));
}
/*
1-----aa
2-----bb
3-----cc
*/
TreeSet<Emp2> ts = new TreeSet<>();
ts.add(new Emp2(1, "zs", 12222));
ts.add(new Emp2(2, "ls", 11));
ts.add(new Emp2(3, "ww", 333));
for (Emp2 e: ts) {
System.out.println(e);
}
/*
id=2, name=ls, salary=11.0
id=3, name=ww, salary=333.0
id=1, name=zs, salary=12222.0
*/
}
}
class Emp2 implements Comparable<Emp2> {
int id;
String name;
double salary;
@Override
public String toString() {
return "id=" + id + ", name=" + name + ", salary=" + salary ;
}
public Emp2(int id, String name, double salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
@Override
public int compareTo(Emp2 o) {
if (this.salary > o.salary) {
return 1;
} else if (this.salary < o.salary) {
return -1;
} else {
if (this.id > o.id) {
return 1;
} else if (this.id < o.id) {
return -1;
} else {
return 0;
}
}
}
}
- Iterator遍历list,map,set
import java.util.*;
public class a {
public static void main(String[] args) {
// 关于list
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(90);
list.add(88);
Iterator<Integer> iter = list.iterator();
for ( ; iter.hasNext(); ) {
Integer value = iter.next();
System.out.println(value);
}
System.out.println("----------");
// 关于set
Set<String> set = new HashSet<>();
set.add("1223");
set.add("2345");
set.add("0000");
Iterator<String> iter2 = set.iterator();
for ( ; iter2.hasNext(); ) {
String value = iter2.next();
System.out.println(value);
}
System.out.println("----------");
Map<Integer, String> map = new HashMap<>();
map.put(100, "aa");
map.put(200, "bb");
map.put(300, "cc");
System.out.println("map法一");
Set<Map.Entry<Integer, String>> entries = map.entrySet();
Iterator<Map.Entry<Integer, String>> iterator = entries.iterator();
for ( ; iterator.hasNext(); ) {
Map.Entry<Integer, String> temp = iterator.next();
System.out.println(temp.getKey() + "---" + temp.getValue());
}
System.out.println("map法二");
Set<Integer> integers = map.keySet();
Iterator<Integer> iterator1 = integers.iterator();
for ( ; iterator1.hasNext(); ) {
Integer next = iterator1.next();
System.out.println(next + "---" + map.get(next));
}
}
}
本文来自博客园,作者:jsqup,转载请注明原文链接:https://www.cnblogs.com/jsqup/p/15883251.html