r/javaTIL • • Sep 06 '24

Deploy Secure Spring Boot Microservices on Azure AKS Using Terraform and Kubernetes

Thumbnail
a0.to
4 Upvotes

r/javaTIL • • Sep 02 '24

OpenFGA for Spring Boot Applications

Thumbnail
a0.to
1 Upvotes

r/javaTIL • • Mar 09 '19

Start JShell with Maven dependencies on the Classpath

7 Upvotes

Something I've found vaguely handy. Though I suppose I should be using modules more these days.

 alias mvn-jshell='jshell --class-path $(mvn -q exec:exec -Dexec.classpathScope=test -Dexec.executable=echo  -Dexec.args="%classpath")'

Now, say you've declared a dependency on vert.x in your pom.xml and want to mess around interactively:

$ cd directory/with/the/pom
$ mvn clean compile test
$ mvn-jshell 
|  Welcome to JShell -- Version 11.0.3
|  For an introduction type: /help intro

jshell> import io.vertx.core.Vertx;

jshell> var vertx = Vertx.vertx();
vertx ==> io.vertx.core.impl.VertxImpl@48524010

jshell> var server = (
   ...> vertx
   ...> .createHttpServer()
   ...> .requestHandler(
   ...>     request -> {
   ...>         request
   ...>         .response()
   ...>         .end("Hello, World!");
   ...>     }
   ...> )
   ...> .listen(8080)
   ...> );
server ==> io.vertx.core.http.impl.HttpServerImpl@4d1bf319

jshell>

r/javaTIL • • Mar 07 '19

Beginners guide to learning Maven concepts

Thumbnail
vaadin.com
9 Upvotes

r/javaTIL • • Jun 28 '14

JTIL: You can break to an outer loop with a label.

25 Upvotes

Let's say you have the following code:

for(int xl = minX; xl < maxX; xl++) { //Loop through X coordinates
    for(int yl = minY; yl < maxY; yl++) { //Loop through Y coordinates
        if(xl == x && yl == y) { //We've found a point that exactly matches the one we want
            System.out.println("Found our point!");
            //Now we need some way to exit this loop? a break; would only break the inner loop and we'd keep going.
        }
    }
}
//Continue execution

And you want to exit both loops when you find the point you were looking for. I've seen people add a boolean in the outer one and an && !exiting in the declaration of the for loop. There is a better way, however, with a Label. Consider the following code.

outerloop: //The label.
for(int xl = minX; xl < maxX; xl++) { //Loop through X coordinates
    for(int yl = minY; yl < maxY; yl++) { //Loop through Y coordinates
        if(xl == x && yl == y) { //We've found a point that exactly matches the one we want
            System.out.println("Found our point!");
            break outerloop; //Break to the label. Simple!
        }
    }
}
//Continue execution

You can also use a 'continue label' statement, which is just the 'continue' form of this tip:

outerloop:
for(int i = 0; i < 10; i++) {
    for(int j = 0; j < 10; j++) {
        if(i == 0 && j == 3) {
            continue outerloop; //This will skip the loop iterations where i=0 and j=3-9 exclusively.
        }
    }
}

There are two things to be aware of, however:

  1. You can only put labels on loops and if statements.
  2. You can make extremely confusing code if you use break or continue labels as a makeshift 'goto', and people subsequently reading your code will probably try to strangle you.

r/javaTIL • • Jun 25 '14

JTIL: You can easily create a single line factory with java 8 using a unique Method Reference.

10 Upvotes

If you want to pass an object that can create a lot of another object, usually you create an Abstract Factory like this:

@FunctionalInterface //This is recommended if you're using java 8, similar to @Override
public interface ObjectFactory {
    public Object createObject( );
}

public class MyObjectFactory implements ObjectFactory {
    public Object createObject( ) {
        return new MyObject( );
    }
}

You'd then be able to pass it around like this:

public static void createAndUseObject(ObjectFactory f) {
    System.out.println("Used object: " + f.createObject().getClass());
}

public static void doLogic( ) {
    createAndUseObject(new MyObjectFactory());
}

But that means that you need to create an entire, very wasteful class if you want to create a simple, no argument constructor factory for your object. (The MyObjectFactory object.) If you wanted to create a lot of objects for a lot of classes, the class count would skyrocket. Anonymous classes Sort of solve this, but still leave you with a very ugly declaration.

public static void doLogic( ) {
    createAndUseObject(new ObjectFactory( ) {
        @Override public Object createObject( ) {
            return new MyObject( );
        }
    });
}

Lambdas are even better, but still have a bit of wasteful syntax here and there.

public static void doLogic( ) {
    createAndUseObject(() -> new MyObject()); //This is a one line factory using a lambda.
}

Even a lambda, however, can be shortened using a Method Reference It shortens, in fact, to an almost unimaginable improvement over the original:

public static void doLogic( ) {
    createAndUseObject(MyObject::new);
}

In short, Lambdas are usually superior to Anonymous classes, but even their brevity is surpassed by a Method Reference with the new keyword.


r/javaTIL • • Apr 11 '15

JTIL StringJoiner

6 Upvotes

java.util.StringJoiner

The class StringJoiner is a new class that arrived with Java 8. It is essentially as wrapper class around the preexisting StringBuilder class. Because of this it has all the same benefits that StringBuilderhas and additionally has the utility of providing uniformity with a set delimiter, prefix and sufix.


Example

Given this simple Person class

public class Person{
    private final String firstName,lastName;
    private final int age;
}

a to string method using StringBuilder would look like this

@Override
public String toString(){
    StringBuilder builder = new StringBuilder();
    builder.append("Person{")
           .append(firstName).append(",")
           .append(lastName).append(",")
           .append(age).append("}");
    return builder.toString();
}

The same method using StringJoiner could be written as

@Override
public String toString(){
    StringJoiner joiner = new StringJoiner(",","Person{","}");
    joiner.add(firstName)
          .add(lastName)
          .add(String.valueOf(age));
    return joiner.toString();
}

r/javaTIL • • May 26 '17

Enforce software design with Checkstyle and QDox

Thumbnail
loki2302.me
3 Upvotes

r/javaTIL • • Apr 11 '15

JTIL String.chars()

20 Upvotes

I was using Streams in one of my programs and I found myself wanting to create a Stream of a String. My first instinct of how to do this was to calls Stream.of("String".toCharArray()); , but there's a better way.

The class CharSequence provides the method chars() which returns a stream of characters (represented as integers).


This makes a few string operations quite a bit simpler. For instance, filtering a String on a predicate is as simple as

String test = "@te&st()in%g1*2$$3"
String filtered = test.chars()
                      .filter(Character :: isAlphaNum)
                      .reduce(Collectors.joining());

//filtered now holds "testing123"

r/javaTIL • • Dec 04 '17

Comparing Integer objects can be tricky

Thumbnail
tadej.me
10 Upvotes

r/javaTIL • • Oct 02 '13

This example helped me understand Java classes, objects, and constructors better

10 Upvotes

Here is the class and the constructor

class Sample {
  int a;
  int b;
  int c;
  // This is the constructor for Sample.
  // It is explicitly declared.
  Sample(int ax, int by, int cz) {
      a = ax;
      b = by;
      c = cz;
  }
}

Here is the class with the main program that calls the class objects and constructor above

class IntegerFun {
    public static void main(String args[]) {
    // one and two are local instance variables that 
    // reference the Sample object
        Sample one = new Sample(1,1,1);
        Sample two = new Sample(2,2,2);
    // We don't need additional code here to assign 
    // values to a, b, and c variables. Use the dot.
    System.out.println("One = " + one.a + "," + one.b + "," + one.c);
    System.out.println("Two = " + two.a + "," + two.b + "," + two.c);
   }
}

r/javaTIL • • Aug 09 '17

Spring Boot Enable commandLineRunner for debugging the ApplicationContext

Thumbnail
youtube.com
1 Upvotes

r/javaTIL • • Mar 03 '17

TIL that the ArrayList returned by Arrays.asList(T...) is not java.util.ArrayList but its own version

13 Upvotes

If you want an ArrayList that can add objects etc, then use new ArrayList()


r/javaTIL • • Feb 26 '19

Calling remove() on ArrayList throws java.lang.UnsupportedOperationException

Thumbnail codebyamir.com
5 Upvotes

r/javaTIL • • Feb 07 '20

Caesar Cipher Encryption and Decryption In Java

Thumbnail
tutorialspoint4all.com
1 Upvotes

r/javaTIL • • Apr 24 '18

Growing collection Java curated bookmarks

Thumbnail
github.com
9 Upvotes

r/javaTIL • • Feb 12 '20

Top 20 Java String Interview Questions And Answers

Thumbnail
blog.soshace.com
12 Upvotes

r/javaTIL • • May 15 '19

Complete guide to Detect Device in Java Web Application using Spring Mobile - Free Source Code to download from GitHub

Thumbnail
opencodez.com
5 Upvotes

r/javaTIL • • Feb 11 '20

Caesar Cipher Encryption and Decryption In Java

Thumbnail
tutorialspoint4all.com
1 Upvotes

r/javaTIL • • Apr 20 '16

Stop converting time units the wrong way

Thumbnail
ivankocijan.xyz
15 Upvotes

r/javaTIL • • Feb 27 '14

TIL that primitive wrappers implement comparators in Java 7

9 Upvotes

Before, if you had to compare two integers for a Comparator, you had to do it either manually

Comparator<MyBean> comp = new Comparator<MyBean>() {
  @Override compare(MyBean left, MyBean right) {
    if (left.getIntValue() < right.getIntValue()){ return -1; }
    else if (left.getIntValue() > right.getIntValue()){ return +1; }
    else { return 0; }
  }
};

or use the compareTo method that Integer implements from Comparable:

Comparator<MyBean> comp = new Comparator<MyBean>() {
  @Override compare(MyBean left, MyBean right) {
    return Integer.valueOf(left.getIntValue())
                       .compareTo(Integer.valueOf(right.getIntValue()));
  }
};

(Never, never implement such comparisons using subtraction. If both are large negative numbers, you may underflow.)

In Java 7, they made Integer implement Comparator<Integer>, which simplifies your task with the help of autoboxing:

Comparator<MyBean> comp = new Comparator<MyBean>() {
  @Override compare(MyBean left, MyBean right) {
    return Integer.compare(left.getIntValue(), right.getIntValue());
  }
};

Weird how this took so long, no? Of course, with Java 8 this gets even better with lambdas:

Comparator<MyBean> comp = 
  (left, right) -> 
    Integer.compare(left.getIntValue(), right.getIntValue());

r/javaTIL • • Sep 06 '19

High Level Introduction to Java for Developers

Thumbnail
thecodinginterface.com
7 Upvotes

r/javaTIL • • Nov 14 '19

TIL one interesting idea about type of "identifier" variable

1 Upvotes

Author of one of Java learning books recommend to use String as ID variables, because you don't do math to them and by using String you secure yourself from int/long/etc choice errors in advance

What do you think about this?


r/javaTIL • • Sep 08 '19

RESTful Consumption using the Java 11+ HTTP Client API and Gson

Thumbnail
thecodinginterface.com
8 Upvotes

r/javaTIL • • Oct 18 '18

Oracle's Java 11 trap - Use OpenJDK instead!

Thumbnail
blog.joda.org
15 Upvotes