DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

bhagvan kommadi
bhagvan kommadi

Posted on

Java Tips

Below are the tips in Java:

Parsing a string into integer

int i=Integer.parseInt("200");

boolean variables
boolean isJavaFun = true;
boolean isFishTasty = false;

JSON parsing in java

import org.json.JSONArray;
import org.json.JSONObject;
public class JSONParsing
{
public static void main(String[] args) throws Exception
{
String jsonInput = "{ 'name': 'thomas','empid':'3',[ {'name': 'Lord','empid':'4'},{'name': 'Sam','empid':'5'}]";
JSONObject outerObject = new JSONObject(jsonInput);
JSONObject innerObject = outerObject.getJSONObject("JObjects");
JSONArray jsonArray = innerObject.getJSONArray("JArray1");
for (int i = 0, size = jsonArray.length(); i < size; i++)
{
JSONObject objectInArray = jsonArray.getJSONObject(i);
String[] elementNames = JSONObject.getNames(objectInArray);
System.out.printf("%d ELEMENTS IN CURRENT OBJECT:\n", elementNames.length);
for (String elementName : elementNames)
{
String value = objectInArray.getString(elementName);
System.out.printf("name=%s, value=%s\n", elementName, value);
}
System.out.println();
}
}}

Comparing String

class StringComparison{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}}

Array List Generics, Lambda and ForEach

ArrayList<String> languages = new ArrayList<>();
languages.add("Java");
languages.add("Python");
languages.add("JavaScript");
System.out.print("ArrayList: ");
languages.forEach((e) -> {System.out.print(e + ", ") }
for (String element : list){
if (element.contains("Java")){
System.out.println(element);
}
}

String splitting, and tokens

String str = "token@thisplace@end";
String[] arrOfStr = str.split("@", 2);
for (String a : arrOfStr)
System.out.println(a)

Handling Spark Data Streams

public static void main(String[] args) {
SparkConf conf = new SparkConf().setMaster("local[2]").setAppName("sparkStreamIng");
JavaStreamingContext javaStreamingContext = new JavaStreamingContext(conf, Durations.seconds(1));
JavaReceiverInputDStream<String> dStream = javaStreamingContext.socketTextStream("localhost", 8080);
JavaDStream<String> errorLine = dStream.filter(new Function<String, Boolean>() {
@Override
public Boolean call(String v1) throws Exception {
return v1.contains("error");
}
});
errorLine.print();
try {
javaStreamingContext.start();
javaStreamingContext.awaitTermination();
} catch (InterruptedException e) {
e.printStackTrace();
}

Randomizing integer between a range

public static int randInt(int min, int max) {
Random rand;
int randomNum = rand.nextInt((max - min) + 1) + min;
return randomNum;
}

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.