Top 10 API Related Questions from Stack Overflow

Stack Overflow is a large repository of valuable programming knowledge. Millions of questions have been answered on Stack Overflow and many answers have very high quality. This is the reason that Stack Overflow answers are often located on the top of the search result from Google.

Even though Stack Overflow has answered a large number of questions, there are still questions being posted every day and many of them remain unanswered or do not get good answers. So the question is how to find answers when Stack Overflow is not enough.

As thousands of programmers use Java APIs and share their projects on Github, those projects should be able to provide good examples for showing how to use Java APIs. Java API Example (jExample: http://www.programcreek.com/java-api-examples/index.php) is a search portal which provide code examples for popular Java APIs.

In this post, I will explore whether using open source code alone (jExample) can answer the top voted API related question or not. “API related questions” refers to the questions that are about how to use APIs to solve a task. The top voted questions from Stack Overflow are analyzed (link: http://stackoverflow.com/questions/tagged/java).

For each question, the best answers are shown first and then the solution from Java API examples (jExample) are illustrated.

1. Iterate through a HashMap

The accepted answer provides this solution:

Map<String, Object> map = ...; 
for (String key : map.keySet()) { 
     // ... 
}

If we search "HashMap" on jExample and go to the example page of java.util.HashMap. And then click one of the most common method - entrySet(), we can quickly get an example like the following:

hashmap-entryset

This example shows how to iterate through an HashMap by using HashMap.entrySet(),Entry.getKey(), and Entry.getValue().

Links: HashMap.entrySet()

2. Create ArrayList from array

For this question, multiple ways are provided from several answers. Here are the top 3 methods:

// Method 1
new ArrayList<Element>(Arrays.asList(array))
// Method 2
ImmutableList.of("string", "elements");
// Method 3
List<String> l1 = Lists.newArrayList(anotherListOrCollection);

The above 3 methods can be found by using jExample.

Method 1:
arrays-aslist

Method 2:
immutiblelist-of

Method 3:
lists-newarraylist

It may not easy to find the second solution if we don't know the class ImmutableList. However, if we go to the example page of ImmutableList, we learn other popular methods of this class.

Links: Arrays.asList(), ImmutableList.of(), Lists.newArrayList()

3. How to generate random integers in a range?

The solution from the accepted answer is:

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

If we go to the java.util.Random class page, we can also get a similar one:

random-next

Link: Random.nextInt()

4. How to convert String to Int?

Best answer:

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

jExample:
integer-parseInt

Link: Integer.parseInt()

5. How to convert InputStream to byte array?

Accepted answer:

InputStream is; 
byte[] bytes = IOUtils.toByteArray(is);

jExample solution:
IOUtils

Links: ByteArrayOutputStream, IOUtils.toByteArray()

6. How to generate an MD5 hash?

The answer mentions MessageDigest.

The jExample can find this example:
messagedigest

Link: MessageDigest

7. How to create a file and write to a file in Java?

Create a text file - method 1

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8"); writer.println("The first line"); 
writer.println("The second line"); 
writer.close();

Create a text file - method 2

List<String> lines = Arrays.asList("The first line", "The second line"); 
Path file = Paths.get("the-file-name.txt"); 
Files.write(file, lines, Charset.forName("UTF-8"));

Examples found on jExample:
Method 1.
filewriter

Method 2.
fileoutputstream

Method 3.
files

Links: FileWriter, FileOutputStream, Files.write()

8. Best way to read a text file in Java?

BufferedReader br = new BufferedReader(new FileReader("file.txt")); 
try {
   StringBuilder sb = new StringBuilder();
   String line = br.readLine();
   while (line != null) {
      sb.append(line);
      sb.append(System.lineSeparator());
      line = br.readLine(); 
   } 
   String everything = sb.toString(); 
} finally { 
   br.close(); 
}

Example from jExample:

inputstreamreader

Links: FileInputStream, FileReader, Files

9. How to convert java.util.Date to XMLGregorianCalendar?

Accepted answer:

GregorianCalendar c = new GregorianCalendar(); 
c.setTime(yourDate); XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c);

From jExample:
xmlgregoriancalendar

DatatypeFactory.newXMLGregorianCalendar()

10. How to check if a String is numeric?

The accepted answer suggests using StringUtils.isNumeric from Apache Commons Lang.

A code example may not necessary for this answer, since the code is just one line. However, if we go to the page of StringUtils, we can see the list of the most common methods of StringUtils. The list is sorted by the popularity. Here is a snapshot of the lsit:
StringUtils

StringUtils

Conclusion

I did find code examples for all the top 10 most voted questions from Stack Overflow. However, jExample requires the user to have some level of knowledge and guess the API class. Some answers may not be obvious, but the jExample still provides supplemental information for using a target API class. The related classes and common methods sidebars are very useful to see the related API classes and the popular methods of the target API class.

Category >> Others  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code> 
String foo = "bar";
</code></pre>