首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Stack Overflow 高票 Java API 問題 Top 10 與開源代碼解法

     編輯:Java 綜合教學

前言

Stack Overflow 擁有海量高質量問答,但尋找最佳實踐仍費時。本文對照 Java API Examples (jExample) 開源代碼庫,為前 10 高票 API 任務提供可直接複製的真實專案片段。

1. 遍歷 HashMap

標準寫法

for (String key : map.keySet()) { ... }

jExample 實戰片段(使用 entrySet() 更高效)

for (Entry<BigInteger, R> colie : subMap.entrySet()) {
    BigInteger col = colie.getKey();
    R vali = colie.getValue();
    ret.setVal(row, col, mutr.mutate(vali));
}

2. 陣列轉 ArrayList

三大高票方案:

// 1. Arrays.asList + new ArrayList()
new ArrayList<>(Arrays.asList(array))

// 2. Guava ImmutableList
ImmutableList.of("a", "b")

// 3. Guava Lists.newArrayList
Lists.newArrayList(anotherCollection)

jExample 驗證三者皆廣泛出現於開源專案。

3. 指定範圍隨機整數

int randomNum = rand.nextInt((max - min) + 1) + min;

4. 字串轉整數

int foo = Integer.parseInt("1234");

5. InputStream 轉 byte[]

byte[] bytes = IOUtils.toByteArray(inputStream);  // Apache Commons IO

6. 產生 MD5 摘要

MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(inputBytes);
byte[] digest = md5.digest();
// 轉十六進制字串...

7. 建立檔案並寫入

// Java 7+ NIO
Files.write(Paths.get("file.txt"),
    Arrays.asList("line1", "line2"), StandardCharsets.UTF_8);

// 或 PrintWriter
try (PrintWriter w = new PrintWriter("file.txt", "UTF-8")) {
    w.println("line1");
}

8. 讀取文字檔全文

String content = new String(Files.readAllBytes(Paths.get("file.txt")), StandardCharsets.UTF_8);

9. Date 轉 XMLGregorianCalendar

GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date);
XMLGregorianCalendar xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);

10. 判斷純數字字串

StringUtils.isNumeric("23432");  // Apache Commons Lang

結語

開源專案代碼是驗證最佳實踐的金標準;善用 jExample 等搜尋引擎,能以實戰片段取代理論爭論。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved