JavaRush /Java Blog /Random EN /Coffee break #163. What is the difference between a lambd...

Coffee break #163. What is the difference between a lambda and a method reference. 5 Ways to Concatenate String Null in Java

Published in the Random EN group

What is the difference between a lambda and a method reference

Source: Reddit IntelliJ IDEA suggests replacing lambda expressions with method references. What is the difference between them? Coffee break #163.  What is the difference between a lambda and a method reference.  5 Ways to Concatenate String Null in Java - 1It turns out there is a subtle difference between lambda expressions and method references. For example, compare: myInstance::getStuff and () ->myInstance.getStuff() . In general, both options are equivalent to each other. But if myInstance is null, and the lambda produces a null pointer when evaluating the lambda, then a method reference will be generated immediately when attempting to access the reference. And what? In general, this is important if the code evaluating the lambda expression is inside a try-catch with a null pointer. For example, I have a function mightBeNull(Supplier<T> function) that does something like this:
try {
    doStuff(function.get().getSomeMore().getSomeMore());
} catch (NullPointerException e) {
    doOtherStuff();
}
If calling mightBeNull(() -> myNullVariable.getStuff()) would work without throwing an exception, then the “equivalent”: mightBeNull(myNullVariable::getStuff) will throw a NullPointerException immediately when the function is called. That's the difference. Note. According to Stackoverflow, if you replace the lambda with a method reference, the class bytecode will be more compact, which means the class will load faster into the JVM. However, in order to experience such a gain, thousands of unoptimized lambdas are needed. However, in a large project such a number can be easily accumulated. Otherwise, the choice between a lambda and a method reference is a matter of taste and code readability. For example, if a lambda has several lines, then readability is reduced, and the code will only benefit if the lambda is placed in a separate method and a reference to it is used.

5 Ways to Concatenate String Null in Java

Source: Gitconnected After reading this post, you will learn more ways to work with strings in Java. Java provides many ways to concatenate strings, but sometimes when we don't pay attention to null strings, we can end up with null, which is obviously not what we want. So use my recommended methods to avoid null values ​​when concatenating String.

Problem Analysis

If we want to concatenate string arrays, we can simply use the + operator. However, we may encounter null values ​​when doing this .
String[] values = {"https", "://", "gist.", "github", ".com", null};
String result = "";

for (String value : values) {
    result = result + value;
}
Combining all these elements leads us to this result:
https://gist.github.comnull
Although we found the problem, the resulting null value is also concatenated as a string, which is clearly not what we were hoping for. And even if we are working on Java 8 or higher, using the static String.join() method to join strings, we will still end up with null values .
String[] values = {"https", "://", "gist.", "github", ".com", null};
String result = String.join("", values);
The result is the same:
https://gist.github.comnull
So how to solve this problem? There are several solutions. To make it easier to demonstrate the code later, we extract a method that can pass a string and return a non-null string.
public String nullToString(String value) {
    return value == null ? "" : value;
}

1. String.concat()

String.concat() is a method that comes with the String class . It is very convenient for string concatenation.
for (String value : values) {
    result = result.concat(getNonNullString(value));
}
Because the nullToString() method is called, there are no null values ​​as a result .

2.StringBuilder

The StringBuilder class provides many useful and convenient methods for constructing strings. The most commonly used among them is the append() method , which uses append() to concatenate strings and is combined with the nullToString() method to avoid null values.
String[] values = {"https", "://", "gist.", "github", ".com", null};
StringBuilder result = new StringBuilder();

for (String value : values) {
    result = result.append(nullToString(value));
}
As a result, you can get the following result:
https://gist.github.com

3. StringJoiner class (Java 8+)

The StringJoiner class provides a more powerful function for joining strings. It can not only specify the delimiter during concatenation, but also specify the prefix and suffix. When concatenating strings, we can use its add() method . The nullToString() method will also be used here to avoid null values.
String[] values = {"https", "://", "gist.", "github", ".com", null};
StringJoiner result = new StringJoiner("");

for (String value : values) {
    result = result.add(nullToString(value));
}

4. Streams.filter (Java 8+)

The Stream API is a powerful stream operations class introduced in Java 8 that can perform standard filtering, matching, traversal, grouping, statistics, and other operations.
  • The filter operation filter can receive a Predicate function .
  • The interface of the Predicate function is the same as the Function interface introduced earlier.
  • This is a functional interface.
  • It can take a generic parameter <T> and the return value is a Boolean type.
  • Predicate is often used for filter data .
So we can define a Predicate to check for null string and pass it to the filter() method from the Stream API. Additionally, you can use the Collectors.joining() method to join the remaining non-null strings.
String[] values = {"https", "://", "gist.", "github", ".com", null};

String result = Arrays.stream(values)
    .filter(Objects::nonNull)
    .collect(Collectors.joining());

5. Use the + operator

Using the + operator may also solve the problem, but it is not recommended. We know that String is an immutable object. Using the + sign often creates a string object, and each time a new string is created in memory, so the performance consumption of using the + sign to concatenate strings is very high.

Conclusion

This article presents several methods for concatenating strings and handling NULLs, in which different methods may be suitable for different scenarios. The analysis shows that the performance of StringBuilder is the best. But in real conditions, you need to combine certain scenarios and then choose the method with the least performance loss.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION