Last active
June 1, 2024 09:43
-
-
Save atonamy/100c2212ebda42825b851429b47e823c to your computer and use it in GitHub Desktop.
[Coderbyte] Technical test for NTUC Singapore (Android Engineer)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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(); | |
} | |
} | |
} |
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
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???