Java中的一些简便操作代码

一,查看指定键

containsKey是Map中的一个接口,用于查看是否包含指定的键,也就是看你要的东西在不在数组里面.

条件是:如果你有一个 Map<K, V>(其中 K 是键的类型,V 是值的类型),你可以使用 containsKey(K key) 方法来检查该Map是否包含特定的键。

代码是:

import java.util.HashMap;

import java.util.Map;



public class Main {

    public static void main(String[] args) {

        Map<String, Integer> map = new HashMap<>();
        map.put("one", 1);
        map.put("two", 2);
        map.put("three", 3);
        if (map.containsKey("two")) {
            System.out.println("The map contains the key 'two'.");
        } else {
            System.out.println("The map does not contain the key 'two'.");
        }
        if (!map.containsKey("four")) {
            System.out.println("The map does not contain the key 'four'.");
        } else {
            System.out.println("The map contains the key 'four'.");
        }
    }
}

这里面就很明显four会输出第一个输出条件。也很方便就检查出来了

二,排序操作

1.Array.sort()

括号中写入要排序的数组,就自动会排序。

但要实现Comparable接口,就可以实现

代码如下:

int[] numbers = {5, 2, 9, 1, 5, 6};
Arrays.sort(numbers);
System.out.println(Arrays.toString(numbers)); // 输出:[1, 2, 5, 5, 6, 9]
2.Collections.sort()
这个是对List集合进行的排序,但也支持实现Comparable接口的对象
代码如下:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Collections.sort(names);
System.out.println(names); // 输出:[Alice, Bob, Charlie]

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值