Java实例——集合

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("集合长度ÿ
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zain_horse

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值