Code Snippets

These are some handy code examples, which are too brief for a full example but still handy:

Logging

You will often see code to get a logger, very often with the class as a parameter something like this:
private static final Logger log = LoggerFactory.getLogger(MyClass.class);
This works from inside MyClass, however you cannot copy and paste this to other classes and will break if you change the class name. I prefer the following:
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
Which you can setup for quick input in your IDE, although you will need to also add:
import java.lang.invoke.MethodHandles

If you are using Lombok then read @Log because this will do all the hard work for you.

Searching for one string in another

There are several ways to do this, as outlined below:

String someText = "Dev,development,test,Test,default";
String seek = "ment";

if (someText.contains(seek.subSequence(0, seek.length()))) {
    System.out.println("it does contain");
} else {
    System.out.println("if does NOT contain");
}
if (someText.indexOf(seek) >= 0) {
    System.out.println("it does contain");
} else {
    System.out.println("it does NOT contain");
}
if (someText.contains(seek)) {
    System.out.println("it does contain");
} else {
    System.out.println("if does NOT contain");
}

There are possibly more, and of course the above is case-sensitive. You can easily stop the case sensitivity with the use of .toLowerCase() on both strings.

For Loops

I keep forgetting how to do the different kinds of loops, so here is an example. The first is the old, classic way, the second is newer and easier and the last is the streams way of doing it.

List<String> stringList = List.of("One", "Two", "Three", "Four");

for (int i = 0; i < stringList.size(); i++) {
    System.out.println(" - a string: " + stringList.get(i));
}

for (String item: stringList) {
    System.out.println(" - a string: " + item);
}

stringList.forEach(item -> {
    System.out.println(" - a string: " + item);
});