# java

A Java method that returns a random boolean value based on a probability alvin June 30, 2019 - 8:14pm

If you ever need a Java method that returns a boolean value based on a given probability, I can confirm that this method works:

``````/**
* `probability` should be given as a percentage, such as
* 10.0 (10.0%) or 25.5 (25.5%). As an example, if `probability`
* is 60% (60.0), 100 calls to this function should return ~60
* `true` values.
* (Note that Math.random returns a value >= 0.0 and < 1.0.)
*/
static boolean getRandomBoolean(float probability) {
double randomValue = Math.random()*100;  //0.0 to 99.9
return randomValue <= probability;
}``````
How to sort data that’s in a Java HashMap (using a TreeMap) alvin June 29, 2019 - 12:32pm

Here’s a brief example of how to sort data that’s already in a Java HashMap. First, some HashMap data:

``````import java.util.*;

Map<Integer, Float> playMap = new HashMap<Integer, Float>() {{
put(10,  1f);
put(12,  2f);
put(15,  4f);
put(18,  6f);
put(20,  6f);
put(25,  7f);
put(30,  6f);
put(35,  5f);
put(40,  5f);
}};``````

A HashMap won’t keep that data in sorted order, so if you want your data sorted, one way to sort it is to add the elements to a Java TreeMap:

## Java: A Java list `tail` function (for ArrayList, LinkedList, etc.)

As a brief note today, I was working on a Java/Android application recently, and I needed a “tail” function when I was working on a Java list. What I mean by that is that Scala has a `tail` function that returns all elements of the list except for the head element, like this:

``````scala> val x = List(1,2,3,4)
x: List[Int] = List(1, 2, 3, 4)

scala> x.tail
res1: List[Int] = List(2, 3, 4)  //head element removed``````

and I wanted the same thing in Java.

Java: Examples of the Java list/array `subList` method (list subset) alvin June 27, 2019 - 12:26pm

As a little note today, if you ever need to extract a subset of a Java list or array, here are some examples of the Java `subList` method:

Free Java and OOP training material alvin March 17, 2019 - 7:33pm

A long time ago — around 2009 — I initially shared some free Java and OOP training material. If you’re interested, you can find it here: