List ordered set, the sequence that is inserted into the storage order
The default order
List<String> list=new ArrayList();
list.add("0");
list.add("4");
list.add("2");
list.add("8");
System.out.println(list.toString());
The output is: [0, 4, 2, 8]
Collections.sort (list): Collections may be provided as a method of sorting a set of
List<String> list=new ArrayList();
list.add("0");
list.add("4");
list.add("2");
list.add("8");
Collections.sort(list);
System.out.println(list.toString());
The output is: [0, 2, 4, 8]
the list.sort () specify the sort comparator
List<String> list=new ArrayList();
list.add("0");
list.add("4");
list.add("2");
list.add("8");
list.sort(new Comparator<String>(){
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
System.out.println(list.toString());
The output is: [8, 4, 2, 0]
Set orderly collection
The default implementation class HashSet sort hashCode value of the internal element
Set<String> set=new HashSet<>();
set.add("武汉");
set.add("加油");
set.add("中国");
set.add("@@");
System.out.println(set.toString());
The output is: [@@, refueling, China, Wuhan]
LinkedHashSet output order may be implemented as a intervening sequence
Set<String> set=new LinkedHashSet<>();
set.add("c");
set.add("i");
set.add("o");
set.add("a");
System.out.println(set.toString());
The output is: [c, i, o, a]
TreeSet implements SortedSet interface which allows orders its stored value (a collection of elements required comparable)
Set<String> set=new TreeSet<>();
set.add("武汉");
set.add("加油");
set.add("中国");
set.add("@@");
System.out.println(set.toString());
The output is: [@@, China, refueling, Wuhan]
May also be specified comparator compares
Set<String> set=new TreeSet<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
set.add("武汉");
set.add("加油");
set.add("中国");
set.add("@@");
System.out.println(set.toString());
The output is: [Wuhan, refueling, China, @@]
Map orderly collection
Output order sequentially inserted LinkedHashMap
Map<String,String> map=new LinkedHashMap<>();
map.put("中国", "加油");
map.put("盂县", "加油");
map.put("山西", "加油");
map.forEach((k,v)->{
System.out.println("k->"+k+"v->"+v);
});
The output is: k-> China v-> Come k-> Yuxian v-> refueling k-> Shanxi v-> refueling
SortedMap TreeMap implements the interface, can be sorted according to the size of natural bond
Map<String,String> map=new TreeMap<>(new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
return o2.compareTo(o1);
}
});
map.put("中国", "加油");
map.put("盂县", "加油");
map.put("山西", "加油");
map.forEach((k,v)->{
System.out.println("k->"+k+"v->"+v);
});
The output is: k-> Yuxian v-> refueling k-> Shanxi v-> refueling k-> China v-> refueling