ArrayList.contains(), size(), clear, asList(), subList(), toArray(), and isEmpty() Example in Java

Java ArrayList Example
ArrayList in Java is one of the most popular Collection classes. ArrayList is an implementation of the List interface via AbstractList abstract class and provides an ordered and an index-based way to store elements. Java ArrayList is analogous to an array, which is also index-based. In fact, ArrayList in Java is internally backed by an array, which allows them to get constant time performance for retrieving elements by index. Since an array is fixed length and you can not change their size, once created, Programmers, starts using ArrayList, when they need a dynamic way to store object, i.e. which can re-size itself. See the difference between Array and List for more differences. 

How to read a File line by line in Java 8 ? BufferedReader lines() + Stream Examples

Hello guy, if you are wondering how to read a file line by line in Java but not sure which class to use then you have come to the right place. Earlier, I have showed you how to read Excel file in Java using Apache POI API and in this article, I am going to tell you about a useful method from BufferedReader class, the lines() method which can be used to read a file line by line. The BufferedReader.lines() is kind of interesting, letting you turn a BufferedReader into a java.util.Stream in Java 8. This is a very powerful thing as it allows you to tread a file as a stream and then you can apply all sorts of Stream methods like map, count, flatMap, filter, distinct, etc to apply the powerful transformation. We will actually see examples of those in this article by finding out the longest line from the file and printing each line of the file.

Difference between HashSet, TreeSet, and LinkedHashSet in Java

Hello guys, in the last article, we have learned about difference between HashMap, TreeMap, and LinkedHashMap and in this article, we are going to learn about difference between HashSet, TreeSet, and LinkedHashSet in Java, another popular Java interview questions for 1 to 2 years experienced developers. If you are doing Java development work then you know that LinkedHashSet, TreeSet, and HashSet are three of the most popular implementations of the Set interface in the Java Collection Framework. Since they implement a Set interface, they follow its contracts for not allowing duplicates but there is a key difference between them in terms of ordering of elements. For example, HashSet doesn't maintain any order, while TreeSet keep elements in the sorted order specified by external Comparator or comparison logic defined in the objects'  natural order. Similarly, LinkedHashSet keep the elements into the order they are inserted.  

10 Examples of ArrayList in Java

ArrayList Example in Java
Hello guys, In this Java ArrayList Tutorial, we will see 10 common usage of ArrayList with examples. You will learn how to add elements in ArrayList, how to remove elements from ArrayList, how to check if ArrayList contains a given object, how to sort an ArrayList of objects  and several other ArrayList functions which we use daily as a Java programmer. ArrayList is one of the most popular classes from the Java Collection framework along with HashSet and HashMap and a good understanding of the ArrayList class and methods is imperative for Java developers. ArrayList is an implementation of List Collection which is ordered and allows duplicates

How to Fix Reference Error: $ is not defined in jQuery and JavaScript [Solved]

Hello JavaScript developer, if you are wondering how to fix the Reference Error $ is not defined while using jQuery then you have come to the right place. "Reference Error: $ is not defined" is one of the common JavaScript errors which come when you try to use $, which is a shortcut of jQuery() function before you load the jQuery library like calling $(document).ready() function. "ReferenceError: XXX is not defined" is a standard JavaScript error, which comes when you try to access a variable or function before declaring it. Since jQuery is also a JavaScript library, you must first include the declaration of the jQuery function or $() before you use it.

How to fix java.net.SocketException: Broken pipe, Connection reset, and Too many open files in Java?

In this blog, I plan to talk about some common exceptions and errors that arise while using sockets. Quite often, these socket issues arise out of application bugs, system settings, or system load. It might be an unnecessary delay to go to product teams, only to discover that the issue can be resolved by tuning/configuring your local settings. Understanding these messages will not only help resolve the issues but also make a conscious effort in avoiding these scenarios while developing applications.

How to fix ArrayIndexOutOfBoundsException and StringIndexOutOfBoundsException in Java?

Though both StringIndexOutOfBoundsException and ArrayIndexOutOfBoundsException are children of IndexOfBoundsException class, the former is thrown by methods of String and related class like StringBuffer and StringBuilder to indicate that an index is either negative or greater than the size of the String, or more generally not valid. For example, charAt() method throws StringIndexOutOfBoundsException when an index is equal to the length of String? why? because String is backed by character array where index starts at 0 and ends at length -1

25 Examples of ConcurrentHashMap in Java

The java.util.ConcurrentHashMap is one of the most important classes of JDK. It was introduced in JDK 1.5 along with other concurrent collection classes like CopyOnWriteArrayList and BlockingQueue. Ever since then, it has been a workhorse in concurrent Java applications. It won't be an exaggeration If I say there is hardly any concurrent Java application that has not used ConcurrentHashMap yet. The class was another implementation of java.util.Map and a popular hash table data structure with concurrency inbuilt. This means you can also pass a ConcurrentHashMap to a method that is expecting a java.util.Map object. It was made scalable by dividing the whole map into a different segment, known as concurrency level, and then allowing threads to modify segments concurrently.

2 Ways to sort a Map in Java by Keys? TreeMap and HashMap Example

So you have a Map in your Java program and you want to process its data in sorted order. Since Map doesn't guarantee any order for its keys and values, you always end up with unsorted keys and Map. If you really need a sorted Map then think about using the TreeMap, which keeps all keys in sorted order. This could be either natural order of keys (defined by Comparable) or custom order (defined by Comparator), which you can provide while creating an instance of TreeMap. If you don't have your data in a sorted Map then the only option that remain for you is to get the keys and values, sort them and then process your Map in that order. 

How to Remove Entry (key/value) from HashMap in Java while Iterating? Example Tutorial

Hello guys, Can you remove a key while iterating over HashMap in Java? This is one of the interesting interview questions as well as a common problem Java developers face while writing code using HashMap. Some programmers will say No, you cannot remove elements from HashMap while iterating over it. This will fail fast and throw concurrent modification exceptions. They are right but not completely. It's true that the iterator of HashMap is a fail-fast iterator but you can still remove elements from HashMap while iterating by using Iterator's remove() method. 

How to Convert a List to Map in Java 8 - Example Tutorial

One of the common tasks in Java programming is to convert a list to a map and I have written about this in the past and today we'll see how Java 8 makes this task easier. Btw, be it Java 7 or Java 8, you need to keep something in mind while converting a list to a map because they are two different data structures and have completely different properties. For example, the List interface in Java allows duplicate elements but keys in a Map must be unique, the value can be duplicated but a duplicate key may cause a problem in Java 8. This means a List with duplicates cannot be directly converted into Map without handling the duplicate values properly. 

How to use Stream and Lambda Expressions to write better code in Java? Examples

Hello guys, writing Clean Code in Java has always been my passion, more so after reading the Clean Code book by legendary author Uncle Bob Martin. I always look for ways to make my concise yet more readable but sometimes Java's verbose nature comes into the way. Thankfully after the introduction of powerful features like Lambda expression and Stream API, writing clean code in Java has become much easier. Streams enable the user to combine commands in some sort of pipeline just like we combine Linux commands using pipe and result in high-quality code which describes what you are doing instead of how to do things.

What is Default or Defender Methods in Java 8? Tutorial Example

Whenever someone talks about Java 8, the first thing they speak about is lambda expression and how lambda expression has changed the way you use Collections API today. In truth, lambda expression would not be that useful had language not been enhanced to support default methods on Java Interface. Also known as virtual extension or defender methods, they allow you to declare a non-abstract method inside the Java interface. This means, finally you can add new methods without breaking all classes, which implements a certain interface. This opens a new path for enhancing and evolving the existing Collection API to take advantage of lambda expressions. For example, now you can iterate over all elements of Collection in just one line, as opposed to four lines it requires you to do prior to Java 8.

How to Convert Stream to List, Set, and Collection in Java 8? Example Tutorial

Hello guys, if you are wondering how to convert a Stream to List, Set, Map, or any other Collection class in Java then you have come to the right place. Earlier, I have shared best Stream and Collection courses, and books as well as many Stream tutorials and in this article, I will tell you how exactly you can use Collectors to convert a Stream to List, Set, Map, or any other Collection class in Java. if you are following Java releases then you know that introduction of the Stream class is one of the most important addition in Java 8 as it makes processing bulk data really easy. Since data is the core part of any application and probably is the most important thing now than ever, a good knowledge of how to use Stream class effectively is important like how to work between Collections and Stream classes. 

Difference between Hibernate, JPA, MyBatis

Hello guys, if you are wondering what is difference between Hibernate, JPA, and MyBatis in Java world and when to use them then you have come to the right place. Earlier, I have shared Hibernate Courses, books, and Interview Questions and in this article, I will answer this popular Hibernate question from Java developer's perspective.  This article aims to give a brief overview of Hibernate, JPA, and MyBatis. Moving ahead highlights the difference between them. It also put light on which underlying technologies they use. Lastly, it provides verdicts on when to use which one among these. But, before we start with the difference between JPA, Hibernate, and MyBatis. It is important to have an understanding of these technologies first.

7 Reasons of NOT using SELECT * in a Production SQL Query? Best Practices

Hello guys, if you are doing a code review and see a SELECT * in production code, would you allow it? Well, its not a simple question as it looks like but let's find out pros and cons about using SELECT * in a production SQL query and then decide. I have read many articles on the internet where people suggest that using SELECT * in SQL queries is a bad practice and you should always avoid that, but they never care to explain why? Some of them will say you should always use an explicit list of columns in your SQL query, which is a good suggestion and one of the SQL best practices I teach to junior programmers, but many of them don't explain the reason behind it. 

How to convert varchar to Date in SQL

You can convert it directly with the CONVERT function by using the style 112 = ISO = yyyymmdd:


DECLARE @date int;


SET @date = 20070701




SELECT CONVERT(datetime, CONVERT(varchar(8), @date), 112)


SELECT CONVERT(datetime, '20070701', 112)


You can get this error Arithmetic overflow error converting expression to data type datetime.

that error came because we were comparing a datetime with int without converting later to datetime.


like

X.PriceDt < A.PrimaryDate


this will fix this

X.ClosePriceDate < CONVERT(datetime, CONVERT(varchar(8), A.PrimaryDate), 112))

How to use Stream allMatch() and anyMatch() function in Java? Example Tutorial

Hello friends, we all know how streams are super important for our day-to-day needs in Java programming and coding nowadays. It allows us to filter data in memory in a declarative way, it also allows us to transform objects as well create a complex Stream pipeline to represent our business logic in a declarative fashion. But, do we know all the stream functionalities? Of course not. Earlier, we have seen examples of filter(), map, flatMap, and findFirst() method and today we will learn two of the most important stream functions anyMatch() and allMatch().  So what’s the wait? Let's start!

How to use Stream findFirst and findAny function in Java? Example Tutorial

Hello friends, here we are again on the journey of Java excited and eager to find the next stop of knowledge. But do not worry my friends, continuing the java stream series further, today we will deep dive into two other functions of streams that are equally important and interesting. Let me start by providing a situation that you guys can analyze and then we will discuss it. Let’s say you have data coming into your code through an API call. Now, you have no idea what the stream of data would be but you want the first element present in it. So, stream provides a function for the same. Let’s see what it is and how it is written.

Java 8 Predicate and Lambda Expression Example

Hello guys, if you want to learn about Predicates in Java 8 and looking for examples then you have come to the right place. In the past, I have explained key Java 8 concepts and classes like Stream, Optional, Collectors etc and we have seen how to use those functional methods like map, filter, and flatmap and in this article, I will show you how to use Predicates in Java 8 with Lambda expression. If you don't know Predicate is a functional interface in Java. A functional interface is nothing but a function with one abstract method or annotated by @FunctionalInterface annotation. Predicate is a functional interface with a function which accepts an object and return Boolean.