1、数组转集合
Arrays.asList(T…);
public static void main(String[] args) throws IOException {
int total = 10;
String[] names = new String[total];
for (int i = 0; i < names.length; i++) {
names[i] = String.valueOf(i);
}
List<String> list = Arrays.asList(names);
for (String s :list) {
System.out.println(s);
}
}
输出结果
0
1
2
3
4
5
6
7
8
9
2、获取集合最值以及使用比较器
Collections.min(T… set, Comparator comparator)
Collections.max(T… set, Comparator comparator)
如果不需要自定义比较器,则采用自然排序比较
Collections.max(T… set)
public static void main(String[] args) throws IOException {
Integer[] integers = new Integer[]{
50,23,53,78,12,43,76};
List<Integer> list = new LinkedList<Integer>();
list.addAll(Arrays.asList(integers));
System.out.print("集合列表:");
for (Integer index :list) {
System.out.print(index+"\t");
}
System.out.println();
System.out.println("集合最小值:"+Collections.min(list, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
}));
System.out.println("集合最大值:"+Collections.max(list, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
}));
}
结果输出
集合列表:50 23 53 78 12 43 76
集合最小值:12
集合最大值:78
3、使用集合迭代器遍历集合
Collection.itarator()
public static void main(String[] args) throws IOException {
HashMap<String,String> hashMap = new HashMap<>(); //哈希集合
hashMap.put("1","1st");
hashMap.put("2","2nd");
hashMap.put("3","3td");
hashMap.put("4","4th");
Collection<String> collections = hashMap.values(); //获取集合超类
Iterator<String> iterator = collections.iterator(); //获取集合迭代器
while (iterator.hasNext()){
//判断是否有下一级项
System.out.println(iterator.next()); //打印迭代器中的值
}
}
输出集合
1st
2nd
3td
4th
4、集合长度
public static void main(String[] args) throws IOException {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("1","1st");
hashMap.put("2","2nd");
hashMap.put("3","3td");
hashMap.put("4","4th");
System.out.println("集合长度ÿ