Posts

Showing posts with the label java 8

Java Jdk8 suportted JacksonUtil

Worries about XML and JSON processing When processing json and xml data in java, there are various third-party libraries for users to choose. Among them are Gson, FastJson, Jackson, Json-lib, xstream, jaxb and so on. Because there are so many options available in Java, if you choose a library to handle json and xml at will, it will not only cause code confusion and difficult to maintain, but also make your jar or war expand in size and increase the release cost. Use Jackson In order to avoid such disasters, we have to find a way to unify the libraries used by programmers when dealing with json and xml data. It is precisely Jackson that is the leader in the above third-party libraries in terms of ease of use, efficiency, and community activity, which can meet our needs. Excellent common-Utils can often support the latest API, and the latest jackson library has fully supported the new date API in jdk8. To use jackson that supports jdk8 date processing API, you need to import t...

Java 8 - stream

Image
stream Stream is an API introduced by java8 that uses lambda expressions heavily. Stream uses an intuitive way similar to querying data from a database with SQL statements to provide a high-level abstraction of Java set operations and expressions. Intuitive means that when writing code, developers only need to focus on what they want instead of focusing on the specific way to achieve the result. In this chapter, we will introduce why we need a new data processing API, the difference between Collection and Stream, and how to apply StreamAPI to our coding. Why do we need a new abstract concept of data processing? In my opinion, there are two main points: The Collection API cannot provide a higher-level structure to query data, so developers have to write a lot of boilerplate code for most trivial tasks. 2. There are certain restrictions on the parallel processing of collection data. How to use the Java language concurrency structure, how to efficiently process data, and how to ...

Java 8 stream filter with object attribute

Java 8 stream filter with object attribute The filter() is an intermediate operation that reads the data from a stream and returns a new stream after transforming the data based on the given condition. Example of Stream Filter(): import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class Example {     public static void main(String[] args) {         List<String> names = Arrays.asList("A","A1","A2","B","B1");         List<String> ListOfName = names.stream()    // converting the list to stream                 .filter(str -> str.length() > 1)   // filter the stream to create a new stream                 .collect(Collectors.toList());  // collect the final stream and convert it to a List         ListOfName.forEach(System.out::println);  ...

Java Predicate Example – Predicate Filter

In mathematics, predicateUsually understood asboolean-valued function 'P: X? {true, false}' 'P: X? {true, false}', Called the predicate on X. You can think of it as an operator or function that returns trueor falsevalues. Java 8 Predicates Usage In Java 8, PredicateYesfunctional interface , So it can be used aslambda expressionOr the allocation target referenced by the method. So, what do you think, we can use these true / false return functions in daily programming? I will say that you can use predicates anywhere you need to evaluate conditions on groups / collections of similar objects so that evaluation can lead to true or false. For example, you canrealtime usecasesUse caserealtime usecases Find all children born after a certain date Pizza set a specific time Employees over a certain age, etc. Java Predicate Class therefore, java predicatesIt seems to be an interesting thing. Let's go deeper. As I said, Predicateyesfunctional interface. This means ...

Java String join() method

Java String join() method String join() method added java 8 (jdk8). This method Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter. method: public static String join​(CharSequence delimiter, CharSequence... elements); delimiter - the delimiter that separates each element elements - the elements to join together. Returns: a new String that is composed of the elements separated by the delimiter Throws: NullPointerException - If delimiter or elements is null Java Program Example: class StringJoin{ public static void main(String args[]){ String message = String.join("-", "Java", "is", "cool");      // message returned is: "Java-is-cool" System.out.println(message); } } output: Java-is-cool

Java ExecutorService Example

An Executor that provides methods to manage termination and methods that can produce a Future for tracking progress of one or more asynchronous tasks. An ExecutorService can be shut down, which will cause it to reject new tasks. Two different methods are provided for shutting down an ExecutorService. The shutdown() method will allow previously submitted tasks to execute before terminating, while the shutdownNow() method prevents waiting tasks from starting and attempts to stop currently executing tasks. Upon termination, an executor has no tasks actively executing, no tasks awaiting execution, and no new tasks can be submitted. An unused ExecutorService should be shut down to allow reclamation of its resources. Method submit extends base method Executor.execute(java.lang.Runnable) by creating and returning a Future that can be used to cancel execution and/or wait for completion. Methods invokeAny and invokeAll perform the most commonly useful forms of bulk execution, executing a c...

Java Data Type Default Values

Image
When a field is declared, It's not always necessary to assign a value. Fields that are declared but not initialized will be set to a reasonable default by the compiler. This default will be zero or null, depending on the data type. The following are the default values for the above data types: Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

Java BlockingQueue Example

Image
BlockingQueue BlockingQueue defines a first-in-first-out data structure that blocks or times out when you attempt to add to a full queue, or retrieve from an empty queue. A Queue operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element. BlockingQueue methods come in four forms, with different ways of handling operations that cannot be satisfied immediately, but may be satisfied at some point in the future: one throws an exception, the second returns a special value (either null or false, depending on the operation), the third blocks the current thread indefinitely until the operation can succeed, and the fourth blocks for only a given maximum time limit before giving up. A BlockingQueue does not accept null elements. Implementations throw NullPointerException on attempts to add, put or offer a null. A null is used as a sentinel value to indicate failure of poll operatio...

Java - Optional Classes

Optional NullPointerExceptions may be the most seen exceptions during Java developers’ daily development. Null reference is considered as The billion dollar mistake by its inventor Tony Hoare¹. Maybe null should not be introduced into Java language in the first place. But it’s already there, so we have to deal with it. Suppose we have a method with argument val of a non-primitive type, we should check first to make sure the value of val is not null. public void myMethod(Object val) { if (val == null) { throw new IllegalArgumentException("val cannot be null!"); } // Use of val } What’s Optional ? Java 8 introduced a new class Optional<T>³ to solve the issues with nulls. The idea behind Optional is quite simple. An Optional object is a holder of the actual object which may be null. Client code interacts with the Optional object instead of the actual object. The Optional object can be queried about the existence of the actual object. Although the actu...