Skip to content

Instantly share code, notes, and snippets.

@atonamy
Last active March 16, 2023 09:54
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save atonamy/100c2212ebda42825b851429b47e823c to your computer and use it in GitHub Desktop.
Save atonamy/100c2212ebda42825b851429b47e823c to your computer and use it in GitHub Desktop.
[Coderbyte] Technical test for NTUC Singapore (Android Engineer)
/*
Java REST GET Simple
In the Java file, write a program to perform a GET request on the route:
https://coderbyte.com/api/challenges/json/rest-get-simple
and then print to the console the hobbies property in the following format:
ITEM1, ITEM2, ...
Example output:
running, painting
*/
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.stream.Collectors;
public class Main {
public static String getStringFromStream(final InputStream inputStream) {
String result = null;
BufferedReader streamReader = null;
try {
streamReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
result = streamReader.lines().collect(Collectors.joining("\n"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;
} finally {
try {
if(streamReader != null)
streamReader.close();
if(inputStream != null)
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String simpleParseArrayProperty(String json, final String propertyName) {
if(json == null)
return null;
int lastIndex = json.lastIndexOf(String.format("\"%s\"", propertyName));
json = json.substring(lastIndex);
lastIndex = json.lastIndexOf("[");
json = json.substring(lastIndex+1);
return json = json
.replaceAll("[\\]}\"]", "")
.replaceAll("\\,", ", ")
.trim();
}
public static void main(String[] args) {
System.setProperty("http.agent", "Chrome");
try {
URL url = new URL("https://coderbyte.com/api/challenges/json/rest-get-simple");
try {
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
System.out.println(simpleParseArrayProperty(getStringFromStream(inputStream), "hobbies"));
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
}
@Sheharyark
Copy link

Main.java:12: error: cannot find symbol
result = streamReader.lines().collect(Collectors.joining("\n"));
^
symbol: variable Collectors
location: class Main
1 error

what kind of error is this???

@YvonneWakamau
Copy link

ensure you import this
import java.util.stream.Collectors;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment