Created
August 15, 2020 18:42
-
-
Save rokon12/c3d9d3db77cbd9569414fcf136456f12 to your computer and use it in GitHub Desktop.
Playground
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
package com.masterdevskills.playground; | |
import java.util.List; | |
import java.util.function.Function; | |
public class BoxingExample { | |
public static void main(String[] args) { | |
long l = System.nanoTime(); | |
for (int i = 0; i < 10_000_000; i++) { | |
heavyLifting(i); | |
} | |
System.out.println("Time: " + (System.nanoTime() - l) / 1_000_000); | |
Function<Long, Long> multiplyBy2 = (x) -> x * 2; | |
int i = heavyLifting(3); | |
List<Integer> integers = List.of(1, 2, 4, 5); | |
final int[] sum = {0}; | |
integers.stream().parallel().forEach(num -> { | |
sum[0] +=num; | |
}); | |
} | |
private static int heavyLifting(Integer i) { | |
int sum = i * i + 3; | |
//System.out.println(sum); | |
return sum; | |
} | |
} |
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
package com.masterdevskills.playground; | |
import java.util.concurrent.locks.Lock; | |
import java.util.concurrent.locks.ReentrantLock; | |
import static com.masterdevskills.playground.LockHelper.withLock; | |
public class ConcurrentIntStack { | |
private int[] elements = new int[16]; | |
private int size = -1; | |
private Lock lock = new ReentrantLock(); | |
public void push(int value) { | |
withLock(lock, () -> { | |
if (size++ >= elements.length) { | |
resize(); | |
} | |
elements[size] = value; | |
}); | |
} | |
private void resize() { | |
} | |
public int pop() { | |
return withLock(lock, () -> { | |
int element = elements[size]; | |
size--; | |
return element; | |
}); | |
} | |
} |
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
package com.masterdevskills.playground; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.function.Function; | |
import java.util.function.Predicate; | |
public class CustomList { | |
private List<Integer> arrayList = new ArrayList<>(); | |
public void add(int... items) { | |
for (int item : items) { | |
arrayList.add(item); | |
} | |
} | |
public CustomList filter(Predicate<Integer> predicate) { | |
List<Integer> filtered = new ArrayList<>(); | |
for (Integer integer : arrayList) { | |
if (predicate.test(integer)) { | |
filtered.add(integer); | |
} | |
} | |
arrayList = filtered; | |
return this; | |
} | |
public synchronized CustomList map(Function<Integer, Integer> function) { | |
List<Integer> converted = new ArrayList<>(); | |
for (Integer integer : arrayList) { | |
Integer apply = function.apply(integer); | |
converted.add(apply); | |
} | |
arrayList = converted; | |
return this; | |
} | |
public double average() { | |
double sum = 0; | |
for (Integer integer : arrayList) { | |
sum += integer; | |
} | |
return sum / arrayList.size(); | |
} | |
public static void main(String[] args) { | |
var customLIst = new CustomList(); | |
customLIst.add(1, 2, 3, 4, 5, 6); | |
customLIst.map((x) -> x * 6) | |
.filter(x -> x % 2 == 0) | |
.average(); | |
} | |
} |
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
package com.masterdevskills.playground; | |
import lombok.Data; | |
import java.util.List; | |
/** | |
* @author A N M Bazlur Rahman @bazlur_rahman | |
* @since 09 August 2020 | |
*/ | |
@Data | |
public class Form { | |
String name; | |
List<Block> blocks; | |
} | |
@Data | |
class Block { | |
String name; | |
List<Field> fields; | |
} | |
@Data | |
class Field { | |
String name; | |
List<Option> options; | |
} | |
@Data | |
class Option { | |
String text; | |
boolean correct; | |
} |
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
package com.masterdevskills.playground; | |
import java.util.concurrent.locks.Lock; | |
import java.util.function.Supplier; | |
public class LockHelper { | |
public static void withLock(Lock lock, Runnable runnable) { | |
lock.tryLock(); | |
try { | |
runnable.run(); | |
} finally { | |
lock.unlock(); | |
} | |
} | |
public static <T> T withLock(Lock lock, Supplier<T> supplier) { | |
lock.tryLock(); | |
try { | |
return supplier.get(); | |
} finally { | |
lock.unlock(); | |
} | |
} | |
} |
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
package com.masterdevskills.playground; | |
import com.github.javafaker.Faker; | |
import lombok.ToString; | |
import java.time.LocalDate; | |
import java.time.Period; | |
import java.time.ZoneId; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
import java.util.stream.IntStream; | |
/** | |
* @author A N M Bazlur Rahman @bazlur_rahman | |
* @since 08 August 2020 | |
*/ | |
//@Data | |
//@AllArgsConstructor | |
//@NoArgsConstructor | |
//@Data | |
//@AllArgsConstructor | |
//@NoArgsConstructor | |
@ToString | |
public class Person implements Comparable<Person> { | |
@Override | |
public int compareTo(Person o) { | |
return o.getFirstName().compareTo(this.firstName); | |
} | |
public enum Gender { | |
MALE, FEMALE | |
} | |
private String firstName; | |
private String lastName; | |
private Gender gender; | |
private LocalDate dob; | |
private String phoneNumber; | |
public int age() { | |
return Period.between(getDob(), LocalDate.now()).getYears(); | |
} | |
public static List<Person> createPeople(int size) { | |
var faker = new Faker(); | |
return IntStream.range(0, size) | |
.mapToObj(index -> { | |
var date = faker.date(); | |
return new Person( | |
faker.name().firstName(), faker.name().lastName(), | |
(index % 2 == 0 ? Gender.MALE : Gender.FEMALE), date.birthday(10, 40).toInstant().atZone(ZoneId.systemDefault()).toLocalDate(), | |
faker.phoneNumber().cellPhone() | |
); | |
}).collect(Collectors.toList()); | |
} | |
public Person(String name) { | |
//System.out.println("constructing person"); | |
this.firstName = name; | |
} | |
public Person(String firstName, String lastName, Gender gender, LocalDate dob, String phoneNumber) { | |
this.firstName = firstName; | |
this.lastName = lastName; | |
this.gender = gender; | |
this.dob = dob; | |
this.phoneNumber = phoneNumber; | |
} | |
public Person() { | |
} | |
public String getFirstName() { | |
return firstName; | |
} | |
public Person setFirstName(String firstName) { | |
this.firstName = firstName; | |
return this; | |
} | |
public String getLastName() { | |
return lastName; | |
} | |
public Person setLastName(String lastName) { | |
this.lastName = lastName; | |
return this; | |
} | |
public Gender getGender() { | |
return gender; | |
} | |
public Person setGender(Gender gender) { | |
this.gender = gender; | |
return this; | |
} | |
public LocalDate getDob() { | |
return dob; | |
} | |
public Person setDob(LocalDate dob) { | |
this.dob = dob; | |
return this; | |
} | |
public String getPhoneNumber() { | |
return phoneNumber; | |
} | |
public Person setPhoneNumber(String phoneNumber) { | |
this.phoneNumber = phoneNumber; | |
return this; | |
} | |
public static void main(String[] args) { | |
/*createPeople(10).forEach(person -> { | |
//System.out.println("person"); | |
var format = String.format("LocalDate.of(%d,%d,%d)", person.getDob().getYear(), person.getDob().getMonth().getValue(), person.getDob().getDayOfMonth()); | |
System.out.println(String.format("new Person(\"%s\",\"%s\",%s,%s,%s)", person.getFirstName(), person.getLastName(), | |
(person.gender == Gender.MALE ? "Gender.MALE" : "Gender.FEMALE"), | |
format, String.format("\"%s\"", person.getPhoneNumber()) | |
)); | |
});*/ | |
} | |
} |
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
package com.masterdevskills.playground; | |
import java.util.ArrayList; | |
import java.util.List; | |
import java.util.function.BinaryOperator; | |
import java.util.function.Function; | |
import java.util.function.Predicate; | |
/** | |
* @author A N M Bazlur Rahman @bazlur_rahman | |
* @since 08 August 2020 | |
*/ | |
public class PersonDemo { | |
public static void main(String[] args) { | |
var person = Person.createPeople(10); | |
var reduce = reduce(person, person1 -> person1.age() > 10, person1 -> person1.getFirstName(), (a, b) -> a + "," + b); | |
System.out.println(reduce); | |
Validator<Person> firstNameNotNull = (Person p) -> p.getFirstName() != null; | |
Validator<Person> secondNameNotNull = (Person p) -> p.getLastName() != null; | |
var validate = firstNameNotNull.and(secondNameNotNull).validate(person.get(0)); | |
System.out.println(validate); | |
} | |
/** | |
* var people = Person.createPeople(10); | |
* <p> | |
* var olderThan = getPeopleOlderThan(people, 18); | |
* System.out.println(olderThan.size()); | |
* <p> | |
* findPeople(people, person -> person.age() >= 18); | |
**/ | |
public static String reduce(List<Person> personList, Predicate<Person> predicate, Function<Person, String> mapper, | |
BinaryOperator<String> combiner) { | |
String accumlate = ""; | |
for (Person person : personList) { | |
if (predicate.test(person)) { | |
var apply = mapper.apply(person); | |
accumlate = combiner.apply(accumlate, apply); | |
} | |
} | |
return accumlate; | |
} | |
public List<String> process(List<Person> personList, Predicate<Person> predicate, | |
Function<Person, String> mapper) { | |
List<String> list = new ArrayList<>(); | |
for (Person person : personList) { | |
if (predicate.test(person)) { | |
list.add(mapper.apply(person)); | |
} | |
} | |
return list; | |
} | |
public static List<Person> getPeopleOlderThan(List<Person> personList, int olderThan) { | |
List<Person> list = new ArrayList<>(); | |
for (Person person : personList) { | |
if (person.age() >= olderThan) { | |
list.add(person); | |
} | |
} | |
return list; | |
} | |
public static List<Person> findPeople(List<Person> personList, SearchCriteria searchCriteria) { | |
List<Person> list = new ArrayList<>(); | |
for (Person person : personList) { | |
if (searchCriteria.test(person)) { | |
list.add(person); | |
} | |
} | |
return list; | |
} | |
interface Validator<Person> { | |
boolean validate(Person person); | |
default Validator<Person> and(Validator<Person> validator) { | |
return (person -> { | |
var isValid = this.validate(person); | |
return (!isValid) ? isValid : validator.validate(person); | |
}); | |
} | |
} | |
interface NotificationReceiver { | |
String receiver(String text); | |
static void setNotification(String str) { | |
} | |
default void setReceiver(String receiver) { | |
} | |
} | |
interface Func<T, R> { | |
default void test() { | |
} | |
} | |
@FunctionalInterface | |
interface Func2<T, R> extends Func<T, R> { | |
void test(T t); | |
} | |
} |
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
package com.masterdevskills.playground; | |
public interface PersonService { | |
Person findBy(String firstName); | |
} |
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
package com.masterdevskills.playground; | |
import java.io.File; | |
import java.time.LocalDate; | |
import java.util.*; | |
import java.util.concurrent.Callable; | |
import java.util.concurrent.ForkJoinPool; | |
import java.util.concurrent.atomic.AtomicInteger; | |
import java.util.function.*; | |
import java.util.stream.Collectors; | |
import java.util.stream.IntStream; | |
import static java.lang.StrictMath.sqrt; | |
import static java.util.stream.LongStream.rangeClosed; | |
/** | |
* @author A N M Bazlur Rahman @bazlur_rahman | |
* @since 08 August 2020 | |
*/ | |
public class Playground { | |
private int x; | |
private void doSomething() { | |
int x; | |
} | |
public static void main(String[] args) { | |
// var x = ""; // Local Type inference | |
// print(x); | |
//Declarative vs Imperative | |
// var x = 99; | |
// var integers = List.of(1, 2, 4, 9, 5, 6, 5, 10); | |
// | |
// //== | |
// boolean found = false; | |
// for (int i = 0; i < integers.size(); i++) { | |
// if (integers.get(i).equals(x)) { | |
// found = true; | |
// } | |
// } | |
//System.out.println("exist: " + found); | |
//what we want | |
//how we want | |
//YakShaving | |
//var contains = integers.contains(x); | |
//select * from users u join something_esle e on e.id =u.id | |
//external iteration | |
// internal | |
// for (int i = 0; i < integers.size(); i++) { | |
// System.out.println(integers.get(i)); | |
// } | |
// | |
// | |
// var executors = Executors.newFixedThreadPool(16); | |
// //100_000_000/16 | |
// for (Integer integer : integers) { | |
// //serial | |
// | |
// } | |
// | |
// | |
// | |
//// LongStream.iterate(0, (value -> value++)) | |
//// .parallel() | |
//// .forEach(value -> { | |
//// | |
//// }); | |
// | |
// integers.parallelStream().forEach(integer -> { | |
// | |
// }); | |
// //Fork/Join Framework | |
// | |
// | |
// integers.forEach(integer -> { | |
// System.out.println(integer); | |
// }); | |
// | |
// var cpuCount = Runtime.getRuntime().availableProcessors(); | |
// System.out.println(" cpuCount: " + cpuCount); | |
// | |
// //What | |
// //How | |
processInt(5); | |
// int x =5; | |
// /// | |
// printIt(x == 3 ? "hello world" : "something else"); | |
// new Thread(() -> System.out.println("Inside another thread: " + Thread.currentThread().getName())).start(); | |
//// () -> { }; | |
// BiFunction<String, String, String> fun = (String x, String y) -> { | |
// return x + "," + y; | |
// }; | |
List<Integer> list = new ArrayList<>(); | |
list.sort(Integer::compare); | |
IntStream.range(0, 100) | |
.filter(i -> i > 5) | |
.boxed() | |
.count(); | |
var people = Person.createPeople(20); | |
peopleOlderThan(people, 10); | |
peopleOlderThan(people, 18, Person.Gender.FEMALE); | |
peopleOlderThan(people, 18, Person.Gender.MALE); | |
var peopleOlderThan21 = filterPeople(people, | |
person -> person.getGender() == Person.Gender.FEMALE | |
&& person.age() > 21); | |
Filtrable<Person> filtrable = person -> | |
person.getGender() == Person.Gender.MALE && person.age() > 60; | |
Filtrable<Person> filter2 = p -> { | |
if (p.age() > 10) { | |
return true; | |
} else { | |
return false; | |
} | |
}; | |
// peron older than 20 but not older than 30 and | |
List<Person> peopleOlderThan160 = filterPeople(people, (p) -> p.age() > 20 && p.age() <= 30); | |
Transformer<Person, String> transformer = (p1) -> p1.getFirstName(); | |
Filtrable<Person> filtrable1 = (p) -> p.age() > 20 && p.age() <= 30; | |
// var strings = filterPeople(people, | |
// filtrable1, | |
// transformer | |
// ); | |
// System.out.println(strings); | |
Transformer<String, Integer> t1 = (value) -> value.trim().length(); | |
Transformer<Person, LocalDate> t2 = (pesron) -> pesron.getDob(); | |
testTransformer(" hello world", t1); | |
Filtrable<String> stringFiltrable = (String s) -> !s.isEmpty(); | |
Filtrable<Integer> integerFiltrable = a -> a > 20; | |
Runnable run = () -> { | |
for (int i = 0; i < 100; i++) { | |
if (i == 55) { | |
break; | |
} | |
} | |
}; | |
new Thread(() -> { | |
while (true) { | |
System.out.println("hello world"); | |
} | |
}); | |
new Thread(() -> { | |
while (true) { | |
System.out.println("hello world"); | |
} | |
}); | |
File file = new File("/Users/rokonoid/projects/advancejava/src/main/java/com/masterdevskills/cha2"); | |
var files = file.listFiles((pathname -> pathname.getName().endsWith(".java"))); | |
// Arrays.asList(files) | |
// .forEach(f -> System.out.println(f.getName())); | |
var people1 = Person.createPeople(20); | |
Comparator<Person> ageComparator = (o1, o2) -> Integer.compare(o1.age(), o2.age()); | |
Collections.sort(people1, ageComparator); | |
Comparator<Person> firstNameComparator = (o1, o2) -> o1.getFirstName().compareTo(o2.getFirstName()); | |
Collections.sort(people1, firstNameComparator); | |
var nums = List.of(1, 2, 3, 4, -1); | |
final var y = 23; | |
nums.forEach(value -> { | |
if (value == y) { | |
System.out.println("matched"); | |
} | |
}); | |
final Person person = new Person(); | |
Executable runnable = () -> { | |
}; | |
Runnable executable = () -> { | |
}; | |
executeAround(runnable); | |
UnaryOperator<String> toUpperCase = (String s) -> s.toUpperCase(); | |
//UnaryOperator | |
var reduce = reduce(people, (p) -> p.getFirstName(), (p1, p2) -> p1 + ", " + p2); | |
// System.out.println( | |
// reduce | |
// ); | |
//map -> reduce | |
IntStream.range(0, people.size()) | |
.mapToObj(index -> new IndexPair(index, people.get(index))) | |
.forEach(indexPair -> { | |
var index = indexPair.index; | |
var t = indexPair.t; | |
}); | |
// ForkJoinPool forkJoinPool = new ForkJoinPool(2); | |
// ForkJoinTask<?> submit = forkJoinPool.submit(() -> { | |
// System.out.println("Thread: " + Thread.currentThread().getName()); | |
// }); | |
// submit.join(); | |
// | |
// forEach(people, (person1 -> { | |
// System.out.println("Thread: " + Thread.currentThread()); | |
// })); | |
long l = System.nanoTime(); | |
// List<Integer> lists = IntStream.range(0, 10_000_000).boxed().collect(Collectors.toList()); | |
// | |
// for (int i = 0; i < lists.size(); i++) { | |
// isPrime(lists.get(i)); | |
// } | |
// | |
// System.out.println("Total: " + (System.nanoTime() - l) / 1_000_000); | |
// l = System.nanoTime(); | |
// | |
// forEach(lists, i -> { | |
// isPrime((i)); | |
// }); | |
// System.out.println("Total: " + (System.nanoTime() - l) / 1_000_000); | |
int x = 4; | |
// int temp = doubleIt(x); | |
// | |
// if (x > 5 && temp > 7) { | |
// System.out.println("Result 1"); | |
// } else { | |
// System.out.println("result 2"); | |
// } | |
var lazy = new Lazy<>(() -> doubleIt(x)); | |
if (x > 5 && lazy.get() > 7) { | |
System.out.println("Result 1"); | |
} else { | |
System.out.println("result 2"); | |
} | |
} | |
public static int doubleIt(int n) { | |
System.out.println("Double it called"); | |
return n * n; | |
} | |
//limitForkJoinPull | |
public static boolean isPrime(long n) { | |
return n > 1 && rangeClosed(2, (long) sqrt(n)) | |
.noneMatch(divisor -> n % divisor == 0); | |
} | |
public static <T> void forEach(List<T> list, Consumer<T> consumer) { | |
int parallelism = 8; | |
var forkJoinPool = new ForkJoinPool(parallelism); | |
Collection<List<T>> partition = partition(list, parallelism); | |
var callables = new ArrayList<Callable<T>>(); | |
for (List<T> ts : partition) { | |
callables.add(() -> { | |
for (T t : ts) { | |
consumer.accept(t); | |
} | |
return null; | |
}); | |
} | |
forkJoinPool.invokeAll(callables); | |
} | |
// public static void forEach(List<Person> personList, Consumer<Person> personConsumer) { | |
// ForkJoinPool forkJoinPool = new ForkJoinPool(4); | |
// Collection<List<Person>> values = partition(personList, 4); | |
// | |
// var list = new ArrayList<Callable<Person>>(); | |
// for (List<Person> value : values) { | |
// Callable<Person> runnable = () -> { | |
// for (Person person : value) { | |
// personConsumer.accept(person); | |
// } | |
// return null; | |
// }; | |
// list.add(runnable); | |
// } | |
// forkJoinPool.invokeAll(list); | |
// } | |
private static <T> Collection<List<T>> partition(List<T> personList, int size) { | |
final AtomicInteger counter = new AtomicInteger(0); | |
return personList.stream().collect(Collectors.groupingBy(p -> counter.getAndIncrement() / size)).values(); | |
} | |
static class IndexPair<T> { | |
private final int index; | |
private final T t; | |
public IndexPair(int index, T t) { | |
this.index = index; | |
this.t = t; | |
} | |
public int getIndex() { | |
return index; | |
} | |
public T getT() { | |
return t; | |
} | |
} | |
public static String reduce(List<Person> personList, Function<Person, String> mapper, | |
BinaryOperator<String> unaryOperator) { | |
String acumulator = ""; | |
for (Person person : personList) { | |
var mapped = mapper.apply(person); | |
acumulator = unaryOperator.apply(acumulator, mapped); | |
} | |
return acumulator; | |
} | |
public static void executeAround(Executable executable) { | |
} | |
public Runnable run() { | |
return () -> { | |
}; | |
} | |
private static Integer testTransformer(String value, Transformer<String, Integer> transformer) { | |
return transformer.transform(value); | |
} | |
private static List<String> filterPeople(List<Person> personList, | |
Predicate<Person> filtrable, | |
Function<Person, String> transformer) { | |
List<String> peopleOlderThan = new ArrayList<>(); | |
for (Person person : personList) { | |
if (filtrable.test(person)) { | |
peopleOlderThan.add(transformer.apply(person)); | |
} | |
} | |
return peopleOlderThan; | |
} | |
private static List<Person> filterPeople(List<Person> personList, | |
Filtrable<Person> filtrable) { | |
List<Person> peopleOlderThan = new ArrayList<>(); | |
for (Person person : personList) { | |
if (filtrable.test(person)) { | |
peopleOlderThan.add(person); | |
} | |
} | |
return peopleOlderThan; | |
} | |
private static List<Person> peopleOlderThan(List<Person> people, int age) { | |
List<Person> peopleOlderThan = new ArrayList<>(); | |
for (Person person : people) { | |
if (person.age() > age) { | |
peopleOlderThan.add(person); | |
} | |
} | |
return peopleOlderThan; | |
} | |
private static List<Person> peopleOlderThan(List<Person> people, int age, Person.Gender gender) { | |
List<Person> peopleOlderThan = new ArrayList<>(); | |
for (Person person : people) { | |
if (person.age() > age | |
&& person.getGender() == gender) { | |
peopleOlderThan.add(person); | |
} | |
} | |
return peopleOlderThan; | |
} | |
@FunctionalInterface | |
interface Filtrable<T> { | |
boolean test(T person); | |
//Single Abstract Method (SAM) | |
} | |
@FunctionalInterface | |
interface Transformer<T, R> { | |
R transform(T t); | |
} | |
private static void printIt(String msg) { | |
System.out.println(msg); | |
} | |
private static void processInt(Integer integer) { | |
//heavy operation | |
} | |
private static void print(String x) { | |
System.out.println(x); | |
} | |
interface Executable { | |
void execute(); | |
default void doSomethingImportant() { | |
//100 | |
x1(); | |
x2(); | |
} | |
private void x1() { | |
} | |
private void x2() { | |
} | |
} | |
static class Lazy<T> { | |
private Supplier<T> theSupplier; | |
private T instance; | |
public Lazy(Supplier<T> theSupplier) { | |
this.theSupplier = theSupplier; | |
} | |
public T get() { | |
if (instance == null) { | |
instance = theSupplier.get(); | |
theSupplier = null; | |
} | |
return instance; | |
} | |
} | |
} |
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
package com.masterdevskills.playground; | |
import java.time.LocalDate; | |
import java.util.function.Function; | |
import java.util.stream.Collectors; | |
/** | |
* @author A N M Bazlur Rahman @bazlur_rahman | |
* @since 09 August 2020 | |
*/ | |
public class Playground2 { | |
public static void main(String[] args) { | |
Function<String, String> heading = (letter) -> LocalDate.now() + "\n" + letter; | |
Function<String, String> footer = (letter) -> letter + "\nThank you"; | |
Letter letter = new Letter("Hello world", heading, footer); | |
System.out.println(letter.text); | |
Form form = new Form(); | |
form.getBlocks().stream() | |
.map(block -> block.getFields()) | |
.collect(Collectors.toList()); | |
} | |
static class Letter { | |
private String text; | |
Letter(String text, Function<String, String>... functions) { | |
Function<String, String> identity = Function.identity(); | |
for (Function<String, String> function : functions) { | |
identity = identity.andThen(function); | |
} | |
this.text = identity.apply(text); | |
} | |
public void setText(String text) { | |
this.text = text; | |
} | |
public String getText() { | |
return text; | |
} | |
} | |
} |
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
package com.masterdevskills.playground; | |
import com.masterdevskills.newjava.Foo; | |
import java.util.ArrayList; | |
import java.util.Collection; | |
import java.util.List; | |
import java.util.Optional; | |
import java.util.concurrent.Callable; | |
import java.util.concurrent.ForkJoinPool; | |
import java.util.concurrent.atomic.AtomicInteger; | |
import java.util.function.BiFunction; | |
import java.util.function.Consumer; | |
import java.util.function.Predicate; | |
import java.util.stream.Collectors; | |
import java.util.stream.IntStream; | |
/** | |
* @author A N M Bazlur Rahman @bazlur_rahman | |
* @since 09 August 2020 | |
*/ | |
public class Playground3 { | |
public static void main(String[] args) { | |
BiFunction<Integer, Integer, Integer> function = (a, b) -> a + b; | |
// System.out.println("hello"); | |
// Consumer func2 = (st) -> System.out.println(st); | |
// System.out.println("hello world"); | |
// func2.accept("hello1"); | |
// String hut = gotoPizzaHut(() -> { | |
// return "Eating pizza "; | |
// }); | |
// System.out.println(hut); | |
// | |
// Callable<String> callable1 = new Callable<>() { | |
// | |
// @Override | |
// public String call() throws Exception { | |
// return ""; | |
// } | |
// }; | |
// Callable<Runnable> x = () -> () -> System.out.println("Hello world"); | |
List<Integer> integers = List.of(1, 2, 3, 4, 5); | |
for (Integer integer : integers) { | |
} | |
// integers.forEach(n -> { | |
// System.out.println(n); | |
// }); | |
// integers.stream() | |
// .filter(number -> number % 2 == 0) | |
// .map(number -> number * 2) | |
// .forEach(n -> { | |
// System.out.println(n); | |
// }); | |
List<Integer> ints = IntStream.range(0, 100_000_000).boxed().collect(Collectors.toList()); | |
// ints.stream().forEach(n -> { | |
// | |
// }); | |
// long start = System.nanoTime(); | |
// | |
// forEach(ints, (n) -> { | |
// boolean prime = isPrime(n); | |
// }, true); | |
// | |
// System.out.println("total time: " + (System.nanoTime() - start) / 1_000_000); | |
//compute(new Foo()); | |
getPersonByName("Bazlur") | |
.ifPresentOrElse(name -> { | |
System.out.println(name); | |
}, () -> { | |
System.out.println("name doesn't exist"); | |
}); | |
} | |
public static void compute(Foo foo) { | |
var bar = foo.getBar(); | |
System.out.println(bar.toString()); | |
} | |
public static Optional<Person> getPersonByName(String name) { | |
// select * from Person p where p.name = nmae; | |
return Optional.empty(); | |
} | |
public static <T> void forEach(List<T> personList, Consumer<T> consumer, boolean runParallel) { | |
if (runParallel) { | |
runParallel(personList, consumer); | |
} else { | |
for (T t : personList) { | |
consumer.accept(t); | |
} | |
} | |
} | |
private static <T> void runParallel(List<T> personList, Consumer<T> consumer) { | |
int i = Runtime.getRuntime().availableProcessors(); | |
ForkJoinPool pool = new ForkJoinPool(i); | |
Collection<List<T>> partitions = partition(personList, i); | |
var list = new ArrayList<Callable<Integer>>(); | |
for (List<T> value : partitions) { | |
Callable<Integer> callable = () -> { | |
for (T t : value) { | |
consumer.accept(t); | |
} | |
return null; | |
}; | |
list.add(callable); | |
} | |
pool.invokeAll(list); | |
} | |
private static <T> Collection<List<T>> partition(List<T> personList, int size) { | |
final AtomicInteger counter = new AtomicInteger(0); | |
return personList.stream().collect(Collectors.groupingBy(p -> counter.getAndIncrement() / size)).values(); | |
} | |
public Runnable getRunnable() { | |
return () -> { | |
System.out.println("Hello world"); | |
}; | |
} | |
class MyRunnable implements Runnable { | |
@Override | |
public void run() { | |
} | |
} | |
public void checkSpelling() { | |
Predicate<String> checker = text -> text.length() > 0; | |
} | |
interface Pizza { | |
String eat(); | |
} | |
public static String gotoPizzaHut(Pizza pizza) { | |
return pizza.eat(); | |
} | |
} |
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
package com.masterdevskills.playground; | |
import java.util.Optional; | |
public class Playground4 { | |
public static void main(String[] args) { | |
// var person = new Person(); | |
// | |
// Validator<Person> validator = ((Validator<Person>) p31 -> p31.getFirstName().isBlank()) | |
// .and(p11 -> p11.getLastName().isBlank()) | |
// .and(p21 -> p21.age() > 18); | |
// | |
// List<Validator<Person>> nameBlank = List.of(p3 -> p3.getFirstName().isBlank(), p1 -> p1.getLastName().isBlank(), p2 -> p2.age() > 18); | |
// | |
// Validator<Person> reduced = nameBlank.stream() | |
// .reduce(p -> true, (v1, v2) -> v1.and(v2)); | |
// boolean validate = reduced.validate(person); | |
// | |
// List<Integer> integers = List.of(1, 2, 3, 4, 5, 6, 7, 8); | |
// Comparator<Integer> compare = Integer::compare; | |
// integers.sort(compare); | |
// | |
// Function<String, Integer> parser = Integer::parseInt; | |
// | |
// | |
// Function<String, Person> function = Person::new; | |
// | |
// List<String> strings = List.of("1", "2", "3"); | |
// | |
// Playground4 playground4 = new Playground4(); | |
// | |
// List<Integer> collect = strings.stream() | |
// .map((playground4::parseToInt)) | |
// .collect(Collectors.toList()); | |
// | |
// | |
// BiFunction<Integer, Integer, Integer> max = Playground4::getMax; | |
// Person bazlur = findBy("bazlur"); | |
// if (bazlur != null) { | |
// System.out.println(bazlur.toString()); | |
// } | |
// Optional<Person> personOptional = findByFirstName("bazlur"); | |
Person person1 = findByFirstName("Bazlur") | |
.orElseGet(Playground4::createDefaultPerson); | |
findByFirstName("Bazlur") | |
.or( () -> Optional.of(createDefaultPerson())) | |
.or(()-> Optional.empty()) | |
.or(()-> Optional.empty()) | |
.or(()-> Optional.empty()) | |
.or(()-> Optional.empty()) | |
.or(()-> Optional.empty()) | |
.or(()-> Optional.empty()); | |
Optional.of(createDefaultPerson()) | |
.orElseThrow(); | |
// List<Integer> | |
// if (personOptional.isPresent()){ | |
// Person person = personOptional.get(); | |
// | |
// } | |
// | |
// personOptional.ifPresent((Playground4::print)); | |
// personOptional.ifPresentOrElse(Playground4::print, Playground4::createPersonAndSaveIt); | |
} | |
private static Person createDefaultPerson() { | |
System.out.println("heavyOp ops "); | |
return new Person("Default Person"); | |
} | |
private static void createPersonAndSaveIt() { | |
//create person | |
// save it | |
// | |
} | |
public static void print(Person person) { | |
System.out.println(person.toString()); | |
} | |
public static Optional<Person> findByFirstName(String name) { | |
//return Optional.of(new Person("Bazlur")); | |
return Optional.empty(); | |
} | |
public static Person findBy(String firstName) { | |
//select * from person where firstName =? | |
return null; | |
} | |
private static Integer getMax(Integer a, Integer b) { | |
return a > b ? a : b; | |
} | |
private int parseToInt(String value) { | |
return Integer.parseInt(value); | |
} | |
} | |
interface Validator<T> { | |
boolean validate(T t); | |
default Validator<T> and(Validator<T> validator) { | |
return (input) -> { | |
boolean isValid = this.validate(input); | |
return !isValid ? isValid : validator.validate(input); | |
}; | |
} | |
} |
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
package com.masterdevskills.playground; | |
import java.util.List; | |
public class Playground5 { | |
// map reduce framework ? | |
public static void main(String[] args) { | |
List<Integer> list = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); | |
// map reduce | |
list.stream() | |
.filter(x -> x % 2 == 0) | |
.filter(x -> x > 5) | |
.filter(x -> x < 100) | |
//.map(x -> heavyOperaiton(x)) | |
.mapToInt(x -> x * 6); | |
//.forEach(x -> System.out.println(x)); | |
// create stream | |
// intermediate ops -> filter, map, | |
// terminal operation -> collect, forEach, | |
} | |
public static void printIt(Integer x) { | |
System.out.println(x); | |
} | |
} |
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
package com.masterdevskills.playground; | |
/** | |
* @author A N M Bazlur Rahman @bazlur_rahman | |
* @since 08 August 2020 | |
*/ | |
public interface SearchCriteria { | |
boolean test(Person person); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment