Skip to content

Instantly share code, notes, and snippets.

@guicaro
Last active February 25, 2024 11:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guicaro/94b535f9995bb136e05fcbf43fbc8190 to your computer and use it in GitHub Desktop.
Save guicaro/94b535f9995bb136e05fcbf43fbc8190 to your computer and use it in GitHub Desktop.
Things to run on a REPL
// Snippets of code that work in Java 8.
// I've compiled these based on problems solved at:
// leetcode.com, interviewbit.com, firecode.io, hackerrank.com
// I strongly recommend you get a Java REPL to play around with some of this code
// (https://github.com/albertlatacz/java-repl)
// You can also use the jshell to run all these commands
// All following lines can be run in a Java REPL
// Note: If you see multiple lines of code, it's better to paste each line separately, just sayin'
// Remember && and || are short circuit operators
// https://users.drew.edu/bburd/JavaForDummies4/ShortCircuitEval.pdf (read page 1 and 7).
// In below example, because first expression is false, the second expression is not evaluated
// Super useful when traversing arrays ;)
if ( true == false && 1 < 100 ) System.out.println("Why not printed?");
// Convert a binary string to Integer
Integer.parseInt("011", 2);
// You can also do a base 10 number
Integer.parseInt("4", 10);
// Remember that substring is (inclusive, exclusive)
"Hello".substring(0,4);
// Returns int value of unicode
Character.getNumericValue('A');
// Is this character a digit?
private boolean isDigit(char x) { return x >= '0' && x <= '9'; }
// From int to String and viceversa :)
String.valueOf(Integer.parseInt("5"));
// Let's throw an exception just for fun
throw new IndexOutOfBoundsException("row index out of bounds");
// You got to love the short form of if-then-else
int result = (true == false) ? 3 : 2;
// Give me a random integer from 0 to 9
Random r = new Random();
r.nextInt(10);
// Problem with above if done in parallel environment, better to use:
ThreadLocalRandom.current().nextInt(1, 10);
// Is a coordinate in 2D array in limits?
private boolean isInLimits(int row, int col, int gridSize) {
return !((row <= 0 || row > gridSize) || (col <= 0 || col > gridSize)); }
// Map an (x,y) in 2 dimensional space to 1 dimensional
public int xyTo1D(int row, int col, int gridSize) { return ((gridSize * row) + col) - gridSize;}
// Initialzie arrays (useful when you need to return one from a function)
int[] myIntArray = new int[]{6,5,2,3,1,4};
// Let's use that cool Enhanced for loop available since Java 5
for(int elem : myIntArray) System.out.println(elem);
// Let's sort that array now, try printing out the array, you can just type the variable name on REPL
Arrays.sort(myIntArray);
// And since we now have a sorted array, let's searh for an item in O(log n) time
Arrays.binarySearch(myIntArray, 5);
// ArrayList with elements in it, long and simple way
List<String> x = new ArrayList<>(Arrays.asList("hi", "hello"));
List<String> z = Arrays.asList"hi", "hello");
// Does not hurt to see capacity of these primitives, watch out for overflow
Long.MAX_VALUE
Integer.MAX_VALUE
// Create an index of the english alphabet using a bit array
boolean [] alphabetBitArray = new boolean [26]
// You can now capture if characer 'b' (lowercase) is in your string
alphabetBitArray['b'-'a'] = true;
// Bit manipulation is magic - Multiply 10 by 2
10 << 1
// How about detecting if a number is even or odd? Also works for negative, read on 2's compliment
(3 & 1) == 1
// Let's play with all the cool stuff with in java.time.* starting in Java 8, thread safe and cool API
import java.time.*
LocalDateTime currentTime = LocalDateTime.now();
Month month = currentTime.getMonth();
// Java8 Periods are pretty cool in java.time
LocalDate date2 = LocalDate.now();
date2 = date2.plusMonths(1);
Period p = Period.between(currentTime.toLocalDate(), date2);
// Java8 We could also get the number of days between the 2 LocalDates
// https://docs.oracle.com/javase/tutorial/datetime/iso/period.html
import java.time.temporal.ChronoUnit;
ChronoUnit.DAYS.between(currentTime.toLocalDate(), date2);
// Java8 There is also Durations for when you are dealling with timestamps
// http://tutorials.jenkov.com/java-date-time/duration.html
Instant t1 = Instant.now();
Instant t2 = Instant.now();
Duration.between(t1,t2).toNanos();
// Reflection, yes please!
// I know, super long topic, but basically the ability to inspect the class.
// Let's look at a String class and invoke the lenght() method. Keep in mind that
// we could have not known it was a String class
import java.lang.reflect.Method;
String name = "Memo";
Method method = name.getClass().getMethod("length", null);
method.invoke(name, null);
// 2d matrix, let's assign values to a MXN matrix (M = 3 and N = 4);
int[][] theMatrix = {{1,0,0,1}, {1,1,0,1}, {1,0,0,1}};
// Java8 Another cool new static method in the String class
String.join("/", "usr", "local", "bin")
// Java7 introduce the Objects class (Yes, Objects with an S at the end)
// Makes it easier to override hashcode(), but performance is mediocre
// https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html#equals-java.lang.Object-java.lang.Object-
// https://www.mkyong.com/java/java-how-to-overrides-equals-and-hashcode/
String name = "Memo";
int id = 12345;
boolean isSingle = true;
Objects.hash(name, id, isSingle);
// Let's override equals and hash. TODO - make a simple class for this
@Override public int hashCode() {
return Objects.hash(lineNum, prefix, areaCode);
}
// Java8 Streams
// Streams have different goals than collections. They are lazy
// Similar to functional paradigm (Scala language)
// https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
ArrayList<String> actors = new ArrayList<>(Arrays.asList("Alice", "Bob", "Jhon", "Ana"));
actors.stream().filter(s -> s.startsWith("A")).forEach(s -> System.out.println(s));
// Java8 Can also do things in parallel
actors.parallelStream().filter(s -> s.startsWith("A")).forEach(s -> System.out.println(s));
// Java8, lets iterate a map
Map<String, Integer> items = Map.of("A", 10, "B", 20, "C", 30, "D", 40);
items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v));
// Java8, more iteration w/ method reference now
List<Integer> numbers = Arrays.asList(5,10,100,1000);
numbers.forEach(i->System.out.println(i))
numbers.forEach(System.out::println)
numbers.stream().filter(n->n.equals(100)).forEach(System.out::println)
// Java8, how about some unlimited streams using iterate() and generate()
// More on collectors here https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html
// Cool guide on streams https://stackify.com/streams-guide-java-8/
Stream.iterate(2, i -> i * 2).limit(5).forEach(System.out::println)
Stream.iterate(2, i -> i * 2).limit(5).collect(Collectors.toList())
Stream.generate(Math::random).limit(5).forEach(System.out::println)
// Java8, more streams and fun with sorting
// Simple Employee class to play with
public class Employee {
String name; int age;
public Employee(String name, int age){ this.name=name; this.age=age;}
public String getName(){ return this.name; }
public int getAge(){ return this.age; }
}
// Crate some employees
List<Employee> employees = List.of(new Employee("Junior", 15), new Employee("Yoda", 100), new Employee("Joe", 30))
employees instanceof Object
employees instanceof List
employees instanceof ArrayList
employees.getClass()
//Ok, let's get a simple ArrayList instead that is mutable
List<Employee> empList = new ArrayList<>(Arrays.asList(new Employee("Junior", 15), new Employee("Yoda", 100), new Employee("Joe", 30)))
//Lets see list w/ unsorted entries
empList.forEach(e -> System.out.println(e.name + " " + e.age))
//Let's sort by name using a comparator and print again
Comparator<Employee> nameComparator = Comparator.comparing(Employee::getName);
Collections.sort(empList, nameComparator);
empList.forEach(e -> System.out.println(e.name + " " + e.age))
// Let's reverse order w/ new comparator
Comparator<Employee> revNameComparator = nameComparator.reversed();
Collections.sort(empList, revNameComparator);
// Last one, how about sorting by name and age? Of course using functionality from Java8
// More info at https://docs.oracle.com/javase/9/docs/api/java/util/Comparator.html
empList.add(new Employee("Joe", 99))
Comparator<Employee> multipleComparator = Comparator.comparing(Employee::getName).thenComparing(Employee::getAge);
Collections.sort(empList, multipleComparator);
//Java 9
var list = List.of(1, 2.0, "3")
Links
https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#getOrDefault-java.lang.Object-V-
https://docs.oracle.com/javase/9/docs/api/java/util/Arrays.html#asList-T...-
https://github.com/winterbe/java8-tutorial#sorted
https://gist.github.com/islomar/b9cc7653a0c4a1cb0afd34c8d77ae806
https://gist.github.com/hamdiank/58c17c05de9623e7a1d77270c4a097c8
https://www.concretepage.com/java/jdk-8/java-8-stream-sorted-example
// More cool things 2024
// Converts List to native array with native int
List<Integer> l = new ArrayList<>();
return l.stream().mapToInt(i->i).toArray();
// Use entry set in a Map
// Create a HashMap and populate it with elements
HashMap<String, Integer> ageMap = new HashMap<>();
ageMap.put("Alice", 30);
ageMap.put("Bob", 25);
ageMap.put("Charlie", 35);
// Using entrySet() to iterate over key-value pairs
for (Map.Entry<String, Integer> entry : ageMap.entrySet()) {
String name = entry.getKey();
Integer age = entry.getValue();
System.out.println(name + " is " + age + " years old.");
}
// stack
Deque<Integer> stack = new ArrayDeque<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println("Stack after pushes: " + stack);
// heap
PriorityQueue<Integer> minHeap = new PriorityQueue<>(); //miin heap
PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Comparator.reverseOrder()); // max heap
// Build heap, the least frequent element first
PriorityQueue<Integer> heap = new PriorityQueue<>(Comparator.comparingInt(frequencyMap::get));
PriorityQueue<Integer> heap = new PriorityQueue<>(Comparator.comparingInt(key -> frequencyMap.get(key)));
PriorityQueue<Integer> heap = new PriorityQueue<>((a, b) -> frequencyMap.get(a) - frequencyMap.get(b));
// 2D Array
boolean[][] a= {{true, false},{false, true}};
boolean[][] a= new boolean[2][2];
// DFS
//
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment