java snippets

JunpuFan
1,041 views
undefined

Open Source Your Knowledge, Become a Contributor

Technology knowledge has to be shared and made accessible for free. Join the movement.

Create Content

README

This playground contains varies java snippets.

To reference snippets, Ctrl-f search topic with :<tag>, such as :Array, :List, :Stream, and jump between them quickly. :<Tag> name are mostly java class/interface names for search consistency.

Note that one snippet can have mutiple :<tag>s.

array initialization - [:Array, :Arrays]

// {...}
System.out.println("quick initialization");
int[] ints1 = new int[] {1, 2, 3, 4, 5};
System.out.println(Arrays.toString(ints1));
System.out.println();
System.out.println("initilize with fixed size");
short[] shorts2 = new short[5];
int[] ints2 = new int[5];
long[] long2 = new long[5];
boolean[] boos2 = new boolean[5];
float[] floats2 = new float[5];
double[] doubles2 = new double[5];
char[] chars2 = new char[5];
byte[] bytes2 = new byte[5];
System.out.println("short[], " + Arrays.toString(shorts2));
System.out.println("int[], " + Arrays.toString(ints2));
System.out.println("long[], " + Arrays.toString(long2));
System.out.println("boolean[], " + Arrays.toString(boos2));
System.out.println("float[], " + Arrays.toString(floats2));
System.out.println("double[], " + Arrays.toString(doubles2));
System.out.println("char[], " + Arrays.toString(chars2));
System.out.println("byte[], " + Arrays.toString(bytes2));
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

List initialization - [:Arrays, :List]

// {...}
System.out.println("quick initialization with Arrays.asList()");
List<String> places = Arrays.asList("Buenos Aires", "Córdoba", "La Plata");
System.out.println(places);
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Loop a List with forEach - [:List, :ArrayList, :forEach]

// {...}
List<String> items = new ArrayList<>();
items.add("A");
items.add("B");
items.add("C");
items.add("D");
items.add("E");
items.forEach(item->System.out.println(item));
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

HashMap example - [:Map, :HashMap]

// {...}
HashMap<String, Integer> map = new HashMap<>();
print(map);
map.put("vishal", 10);
map.put("sachin", 30);
map.put("vaibhav", 20);
System.out.println("Size of map is:- " + map.size());
print(map);
if (map.containsKey("vishal")) {
Integer a = map.get("vishal");
System.out.println("value for key \"vishal\" is:- " + a);
}
map.remove("vishal");
print(map);
map.clear();
print(map);
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Frequency Map - [:Map, :HashMap]

// {...}
frequencyMap(new int[] {1, 1, 2, 2, 3, 3}).forEach((k, v) -> System.out.println(k + " " + v));
}
private static Map<Integer, Integer> frequencyMap(int[] arr) {
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < arr.length; i++) {
if (map.containsKey(arr[i]))
map.put(arr[i], map.get(arr[i]) + 1);
else
map.put(arr[i], 1);
}
return map;
}
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Loop a Map with forEach - [:List, :forEach]

// {...}
Map<String, Integer> items = new HashMap<>();
items.put("A", 10);
items.put("B", 20);
items.put("C", 30);
items.put("D", 40);
items.put("E", 50);
items.put("F", 60);
items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

quick array sum with Stream - [:Stream, :IntStream]

// {...}
int sum1 = IntStream.of(1,2,3).sum();
System.out.println(sum1);
int sum2 = Arrays.stream(new int[] {1,2,3}).sum();
System.out.println(sum2);
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

quick index range with IntStream - [:Stream, :IntStream]

// {...}
int[] index1 = IntStream.range(0, 10).toArray();
System.out.println(Arrays.toString(index1));
int[] index2 = IntStream.rangeClosed(0, 9).toArray();
System.out.println(Arrays.toString(index2));
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

stream().map().collect() example - [:Stream]

// {...}
List<String> alpha = Arrays.asList("a", "b", "c", "d");
List<String> collect = alpha.stream().map(String::toUpperCase).collect(Collectors.toList());
System.out.println(collect);
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

stream().filter().map().sorted().forEach() example - [:Stream]

// {...}
List<String> myList =
Arrays.asList("a1", "a2", "b1", "c2", "c1");
myList
.stream()
.filter(s -> s.startsWith("c"))
.map(String::toUpperCase)
.sorted()
.forEach(System.out::println);
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

StringBuilder example - [:String, :StringBuilder]

// {...}
String str = "hello";
// conversion from String object to StringBuilder
StringBuilder sbl = new StringBuilder(str);
sbl.append(" world");
String str1 = sbl.toString();
System.out.println(str1);
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Lambda Expressions example - [:Lambda]

Syntax

lambda operator -> body

// {...}
// Creating an ArrayList with elements
List<Integer> arrL = Arrays.asList(1, 2, 3, 4);
// Using lambda expression to print all elements of arrL
arrL.forEach(n -> System.out.println(n));
// Using lambda expression to print even elements of arrL
arrL.forEach(n -> { if (n%2 == 0) System.out.println(n); });
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Convert Date to Timestamp - [:Date, :Timestamp, :SimpleDateFormat]

// {...}
Date date = new Date();
Timestamp ts=new Timestamp(date.getTime());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(formatter.format(ts));
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Convert Date to String - [:Date, :SimpleDateFormat]

// {...}
Date date = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
String strDate = formatter.format(date);
System.out.println("Date Format with MM/dd/yyyy : "+strDate);
formatter = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
strDate = formatter.format(date);
System.out.println("Date Format with dd-M-yyyy hh:mm:ss : "+strDate);
formatter = new SimpleDateFormat("dd MMMM yyyy");
strDate = formatter.format(date);
System.out.println("Date Format with dd MMMM yyyy : "+strDate);
formatter = new SimpleDateFormat("dd MMMM yyyy zzzz");
strDate = formatter.format(date);
System.out.println("Date Format with dd MMMM yyyy zzzz : "+strDate);
formatter = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z");
strDate = formatter.format(date);
System.out.println("Date Format with E, dd MMM yyyy HH:mm:ss z : "+strDate);
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

enum example [:enum]

// {...}
public enum SomeStuff {
AAA(1, "aaa"),
BBB(2, "bbb"),
CCC(3, "ccc");
public int id;
public String name;
SomeStuff(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
}
public static void main(String[] args) {
SomeStuff[] stuffs = SomeStuff.values();
for (SomeStuff stuff : stuffs) {
System.out.println("id : " + stuff.getId() + " name: " + stuff.getName());
}
}
//{...}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Open Source Your Knowledge: become a Contributor and help others learn. Create New Content