“Stuff I always forget how to do and have to google it” This is a small collection of useful list functions to use on Kotlin. Lists used in this examples val myModels = listOf( MyModel(1,"Abraham"), MyModel(2, "Bruno"), MyModel(3, "Carlos"), MyModel(4, "Daniel"), MyModel(5, "Eduard"), MyModel(6, "Fabio"), MyModel(7, "Akira"), MyModel(8, "Alberto") ) val myModels2 = listOf( MyModel(9, "Maria"), MyModel(10, "Julia"), MyModel(11, "Rebeca") ) val listOfLists = listOf(myModels, myModels2) val myModelsMutable = mutableListOf( MyModel(1,"Abraham"), MyModel(2, "Bruno"), MyModel(3, "Carlos"), MyModel(4, "Daniel"), MyModel(5, "Eduard"), MyModel(6, "Fabio"), MyModel(7, "Akira"), MyModel(8, "Alberto") ) Filter out items val filtered = myModels.filter { it.name.startsWith("A") } assertThat(filtered).hasSize(3) assertThat(filtered[0].name).isEqualTo("Abraham") println(filtered) //[MyModel(id=1,...
Posted on Aug 15, 2020
“Stuff I always forget how to do and have to google it” The main difference between async vs launch is that async can return a value and launch cannot On Async statement runBlocking { val job = async { println("Running on the background!") Thread.sleep(1000) "this is done!" } println("Response is ${job.await()}") } This will print “Response is this is done!” Similar thing on Launch statement runBlocking { val job = launch { println("Running on the background!") Thread.sleep(1000) // "this is done!" -> useless statement :( } // -- await() doesn't work :( // println("Response is ${job.await()}") job.join() } How to...
Posted on Aug 14, 2020
“Stuff I always forget how to do and have to google it” Step 1 - create channel reader or processor (in parallel) private fun CoroutineScope.createProcessorJob(channel: Channel<String>): Job { return launch { //process untill channel closed for (message in channel) { println("PROCESSOR: processing ->$message<-") Thread.sleep(500) } println("OMG, THE CHANNEL IS CLOSED!") } } Step 2 - create channel sender or producer (in parallel) private fun CoroutineScope.sendListToChannel(list: List<String>, channel: Channel<String>): MutableList<Job> { val senderJobs = mutableListOf<Job>() list.forEach { val job = launch { channel.send("Hey processor, process $it") println("Sending super duper fast, until the capacity is hit.") } senderJobs.add(job) } return senderJobs }...
Posted on Aug 13, 2020
“Stuff I always forget how to do and have to google it” Processing a list in parallel on Kotlin using coroutines, using 2 threads: Obs: Remember to close the context! val list = listOf("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O") val context = Executors.newFixedThreadPool(1).asCoroutineDispatcher() runBlocking { list.forEach { launch(context) { val time = measureTimeMillis { delay(3000) // this frees up the thread to other tasks // Thread.sleep(3000) // this does NOT free up the thread to other tasks println("Finished $it - ${now()}") } println("$it took $time milliseconds") } } } context.close() Processing...
Posted on Aug 12, 2020
“Stuff I always forget how to do and have to google it”
Calculate elapsed in millis in kotlin:
val elapsed = measureTimeMillis {
Thread.sleep(1000L)
}
assertThat(elapsed).isGreaterThan(1000L)
Calculate elapsed in seconds, nano seconds, milliseconds:
val elapsed = measureTime {
Thread.sleep(1100L)
}
assertThat(elapsed.inSeconds).isGreaterThan(1.0)
println("micro=${elapsed.inMicroseconds}, nano=${elapsed.inNanoseconds}, milli=${elapsed.inMilliseconds}")
Obs: Needs @ExperimentalTime annotation
Source code: Here
Posted on Aug 11, 2020
This is an alternate solution when verifying if a String is an anagram. The algorithm: For both Strings: Remove special characters (!,’.) For both Strings: Split the String into array of characters Iterate both arrays and check if they have same size and characters are the same To remove the special characters we can use regex: public class SpecialCharRemover { public static String removeSpecial(String s1){ if(isNull(s1)){ return null; } return s1.replaceAll("[^\\w\\s]",""); } } Creating character map public class CharMap { public static Map<String, Integer> getCharMap(String s){ if(isNull(s)){ return new HashMap<>(); } Map<String, Integer> charMap = new HashMap<>(); for(String curr :...
Posted on Jun 23, 2018
Another common Java exercise is to verify if two Strings are anagrams The algoritm is: For both Strings: Remove special characters (!,’.) For both Strings: Split the String into array of characters For both Strings: Create a Character Map, with key = char, value = number of occurences of char Iterate the array of characters and calculate the CharacterMap Verify if both Maps are equal To remove the special characters we can use regex: public class SpecialCharRemover { public static String removeSpecial(String s1){ if(isNull(s1)){ return null; } return s1.replaceAll("[^\\w\\s]",""); } } Creating character map public class CharMap { public static...
Posted on Jun 23, 2018
Another common Java exercise is to verify if a String is a Palindrome
The algorithm is:
Split the String into an array with all the characters
Reverse the array
Join the array again
Check if the reversed string is equal to the input
Reversing the array
public class StringReverser {
public static String reverse(String s1){
if(isNull(s1)){
return null;
}
List<String> charList = asList(s1.split(""));
Collections.reverse(charList);
return String.join("", charList);
}
}
Palindrome class
public class Palindrome {
public static boolean isPalindrome(String s1){
if(isNull(s1)){
return false;
}
String reversed = StringReverser.reverse(s1);
return reversed.equals(s1);
}
}
Source code: Palindrome
Posted on Jun 22, 2018
This is an alternate solution for reversing Strings in java The algorithm: Split the String into an array with all the characters Iterate throught the array, starting from the last position and adding into a new string public static String reverse(String s1) { if(isNull(s1)){ return null; } StringBuilder stringBuilder = new StringBuilder(); String[] splitted = s1.split(""); for (int i = splitted.length - 1; i >= 0; i--) { stringBuilder.append(splitted[i]); } return stringBuilder.toString(); } Tests: @Test public void reverse1(){ String entry = "ABCDEF"; String expected = "FEDCBA"; String result = StringReverserByConcat.reverse(entry); assertEquals(expected, result); } @Test public void reverseNull(){ String entry =...
Posted on Jun 21, 2018
Reverse a string is a common exercise and this is a simple Java solution The algorithm is: Split the String into an array with all the characters Reverse the array Join the array again public static String reverse(String s1){ if(isNull(s1)){ return null; } List<String> charList = asList(s1.split("")); Collections.reverse(charList); return String.join("", charList); } Tests: @Test public void reverse1(){ String entry = "ABCDEF"; String expected = "FEDCBA"; String result = StringReverser.reverse(entry); assertEquals(expected, result); } @Test public void reverseNull(){ String entry = null; String expected = null; String result = StringReverser.reverse(entry); assertEquals(expected, result); } @Test public void reverseEmpty(){ String entry = ""; String...