欢迎访问宙启技术站
智能推送

10个有用的Java函数

发布时间:2023-05-21 19:35:52

1. String.split()

这个函数可以将一个字符串分割成多个字符串,每个分割都是通过一个给定的字符或字符串进行的。分割后的字符串可以存放到一个数组中。如下示例,将字符串s1按照空格进行分割:

String s1 = "Hello World!"

String[] words = s1.split(" ");

2. Arrays.asList()

这个函数可以将一个数组转换成一个集合。可以方便的在集合中进行元素的添加、删除和遍历。如下示例,将一个字符串数组转换为List集合:

String[] str_array = {"a", "b", "c"};

List<String> str_list = Arrays.asList(str_array);

3. Collections.sort()

这个函数可以对List集合进行排序。可以根据升序或降序进行排序。如下示例,对一个字符串集合按照字典序进行降序排序:

List<String> str_list = Arrays.asList("c", "a", "m", "d", "z");

Collections.sort(str_list, Collections.reverseOrder());

4. Math.round()

这个函数可以对浮点数进行四舍五入。如下示例,将一个浮点数四舍五入为整数:

double d = 2.356;

long l = Math.round(d);

5. Calendar.getInstance()

这个函数可以获取一个Calendar实例。可以用这个实例获取当前时间的年、月、日等信息。如下示例,获取当前年份:

Calendar c = Calendar.getInstance();

int year = c.get(Calendar.YEAR);

6. String.format()

这个函数可以将多个参数以指定的格式转换为一个字符串。在转换的过程中,可以指定格式化的参数类型、数值、宽度、精度等。如下示例,将一个整数按照指定格式转换为字符串:

int i = 255;

String s = String.format("%08x", i);

7. StringBuilder.append()

这个函数可以向一个字符串中添加字符、字符串、整数等。可以连续添加多个元素,最后得到一个新的字符串。如下示例,将多个字符串拼接为一个新的字符串:

String s1 = "Hello, ";

String s2 = "World!";

StringBuilder sb = new StringBuilder();

sb.append(s1).append(s2);

String result = sb.toString();

8. File.exists()

这个函数可以检测一个文件或目录是否存在。如果存在返回true,否则返回false。如下示例,检测一个文件是否存在:

File file = new File("myfile.txt");

if (file.exists()) {

   // do something

}

9. System.arraycopy()

这个函数可以将一个数组的中某一段元素复制到另一个数组中的某一段。可以方便的将两个数组合并或切割。如下示例,将一个数组中的元素复制到另一个数组中:

int[] array1 = {1, 2, 3, 4, 5};

int[] array2 = new int[3];

System.arraycopy(array1, 1, array2, 0, 3);

10. Scanner.nextLine()

这个函数可以从标准输入流中读取一行。可以读取用户输入的字符串,数字、布尔类型等。如下示例,从标准输入中读取一行字符串:

Scanner sc = new Scanner(System.in);

String str = sc.nextLine();