JavaRush /Java Blog /Random EN /Coffee break #217. How to initialize List in Java. 7 Simp...

Coffee break #217. How to initialize List in Java. 7 Simple Tricks to Improve Java Productivity: Tips and Examples

Published in the Random EN group

How to initialize List in Java

Source: FreeCodeCamp This article covers various List initialization methods in Java with practical examples. Coffee break #217.  How to initialize List in Java.  7 Simple Tricks to Improve Java Productivity: Tips and Examples - 1One of the basic data structures in the Java language is the List . It allows developers to store and manage a set of elements. Initializing a List in Java is an important step in the development process because it defines the initial state of the List and prepares it for further operations. There are various ways to initialize a List in Java, the choice depends on the specific requirements of the project:
  • Using the ArrayList constructor .
  • Using the add() method .
  • Using the Arrays.asList() method .
  • Using the Stream.of() method .
Let's take a closer look at these methods.

How to initialize a list using the ArrayList constructor

In Java, the ArrayList class is an implementation of the dynamic array interface List , allowing you to add and remove elements from a list as needed. The ArrayList class provides several constructors for creating an instance of the class. The syntax to create an ArrayList object without an initial capacity is:
ArrayList<Object> list = new ArrayList<Object>();
The no-argument constructor creates an empty list ( List ) with an initial capacity of 10 elements. If the list exceeds this capacity, the ArrayList class automatically increases the capacity by creating a new, larger array and copying the elements from the old array to the new array. Alternatively, we can create an ArrayList object with an initial capacity using a constructor with one integer argument, where capacity is the initial capacity of the list:
ArrayList<Object> list = new ArrayList<Object>(capacity);
To initialize a List with values, we can use a constructor that takes a Collection as an argument. You can pass any collection object that implements the Collection interface to this constructor , such as another ArrayList or LinkedList . The collection's elements are added to the new ArrayList in the order in which they appear in the collection. Here's an example of how to create an ArrayList and initialize it with values ​​using a constructor that takes a Collection :
import java.util.ArrayList;
import java.util.Arrays;

public class Example {
    public static void main(String[] args) {
        // создаем массив целых чисел
        Integer[] array = {1, 2, 3, 4, 5};

        // создаем список из массива
        ArrayList<Integer> list = new ArrayList<Integer>(Arrays.asList(array));

        // печатаем список
        System.out.println(list); // [1, 2, 3, 4, 5]
    }
}
In this example, we create an array of integers and then pass it to the Arrays.asList() method to create a List object . We then pass this List object to the ArrayList constructor to create a new ArrayList with the same elements as the original array. Finally, we print the contents of the list using the System.out.println() method .

How to initialize List using add() method

The add() method is widely used in Java to add elements to a collection or list. This method is available for several collection types in Java, including List , Set , and Map . The add() method takes one argument—the element to be added to the collection. When it comes to adding elements to a vList , the add() method is especially useful because lists in Java are ordered collections that can contain duplicates. The add() method can be used to add elements to the end of a list, making it a convenient way to initialize a List with some initial values. Here is an example of how to use the add() method to initialize a List in Java:
import java.util.ArrayList;
import java.util.List;

public class ListExample {
    public static void main(String[] args) {
        // создаем новый ArrayList
        List<String> myList = new ArrayList<>();

        // добавляем элементы в список, используя метод the add()
        myList.add("apple");
        myList.add("banana");
        myList.add("cherry");

        // печатаем содержимое списка
        System.out.println(myList);
    }
}
In this example, we first create a new ArrayList named myList . We then use the add() method to add three strings ("apple", "banana" and "cherry") to the end of the list. We then print the contents of the list using the System.out.println() method . When we run the program, the output will be like this:
[apple, banana, cherry]

How to initialize List using Arrays.asList() method

Java's built-in Arrays.asList() method converts an array into a list. This method takes an array as an argument and returns a List object . The object returned by the Arrays.asList() method is a fixed-size list, which means we cannot add or remove elements from it. To use the Arrays.asList() method to initialize a List in Java, we have to follow the following steps: First, let's declare an array of elements with which we want to initialize the list. For example, suppose we want to initialize a list with three elements: "apple", "banana" and "orange". Here we can declare an array like this:
String[] fruits = {"apple", "banana", "orange"};
Then we call the Arrays.asList() method and pass the array as an argument. This will return a List object containing the elements of the array.
List<String> fruitList = Arrays.asList(fruits);
Now we can use the fruitList object to access the elements of the list. For example, we can iterate through a list and print each element:
for (String fruit : fruitList) {
    System.out.println(fruit);
}
Conclusion:
apple banana orange
It's important to note that the Arrays.asList() method does not create a new List object , but rather returns a List object representation of the original array . This means that if we change the original array, the changes will also be reflected in the List object . For example:
fruits[0] = "pear";
System.out.println(fruitList.get(0)); // Вывод: pear
In the above example, we changed the first element of the fruits array to "pear". When we access the first element of the fruitList object , we also get "pear" because fruitList is simply a representation of the fruits array .

How to initialize List using Stream.of() method

Stream.of() is a convenience method provided by Java 8 and later in the java.util.stream package . It is used to create a stream of elements of any type, including primitive types, arrays, and objects. This method takes one or more arguments and returns a stream consisting of those arguments. Syntax of the Stream.of() method :
Stream<T> stream = Stream.of(t1, t2, t3, ..., tn);
Here T is the type of elements in the stream, and t1 and further up to tn are the elements that should be included in the stream. To initialize a List in Java using the Stream.of() method , you need to do the following:
  1. First import the java.util.stream package .

  2. Then use the constructor to create a list of the desired ArrayList type, for example:

    List<String> myList = new ArrayList<>();
  3. Initialize the list using the Stream.of() method , passing the desired elements as arguments, and then use the collect() method to collect the stream elements into a list, for example:

    myList = Stream.of("Apple", "Banana", "Cherry", "Date")
                  .collect(Collectors.toList());
  4. We can then print the list to check its contents.

    System.out.println(myList);

    Conclusion:

    [Apple, Banana, Cherry, Date]

Conclusion

Initializing a List in Java is a fairly common programming task, and there are several ways to do it. By following the steps described in this article, we can easily create and initialize a List with the desired elements using the Stream.of() method . This approach is concise and flexible, and can be especially useful when we need to initialize a list with a small number of elements. Happy coding!

7 Simple Tricks to Improve Java Productivity: Tips and Examples

Source: Medium Here is a selection of seven practical tips that, if followed, will help improve the productivity of a Java developer. You can improve the performance of your Java applications by following a few simple tips.

1. Use primitive types instead of objects:

// Плохо: использование an object Integer
Integer count = 0;
for (int i = 0; i < 1000000; i++) {
    count++;
}

// Хорошо: использование примитива int
int count = 0;
for (int i = 0; i < 1000000; i++) {
    count++;
}

2. Avoid creating unnecessary objects:

// Плохо: использование конкатенации строк с помощью '+'
String str = "";
for (int i = 0; i < 10000; i++) {
    str += i;
}

// Хорошо: использование StringBuilder
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10000; i++) {
    sb.append(i);
}
String str = sb.toString();

3. Use the correct data structure:

// Плохо: использование List для частого поиска
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// ...
if (names.contains("Charlie")) {
    // ...
}

// Хорошо: использование HashSet для частого поиска
Set<String> names = new HashSet<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");
// ...
if (names.contains("Charlie")) {
    // ...
}

4. Minimize method calls:

// Плохо: вызов метода внутри цикла
for (int i = 0; i < 1000000; i++) {
    doSomething(i);
}

// Хорошо: выносим метод за пределы цикла
for (int i = 0; i < 1000000; i++) {
    // ...
}
doSomething(i);

5. Use static and final modifiers:

// Плохо: создание ненужных экземпляров an objectов
public class MyClass {
    private int value;
    public void setValue(int value) {
        this.value = value;
    }
    public int getValue() {
        return value;
    }
}
MyClass obj = new MyClass();
obj.setValue(10);
int value = obj.getValue();

// Хорошо: использование статических и финальных модификаторов
public class MyClass {
    private static final int DEFAULT_VALUE = 0;
    private final int value;
    public MyClass(int value) {
        this.value = value;
    }
    public int getValue() {
        return value;
    }
}
MyClass obj = new MyClass(10);
int value = obj.getValue();

6. Use an algorithm appropriate to the situation:

// Плохо: использовать линейный поиск для большой коллекции
List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// ...
int target = 7;
for (int i = 0; i < nums.size(); i++) {
    if (nums.get(i) == target) {
        // ...
    }
}
// Хорошо: использование бинарного поиска для большой коллекции
List<Integer> nums = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// ...
int target = 7;
int index = Collections.binarySearch(nums, target);
if (index >= 0) {
    // ...
}

7. Optimize your cycles:

// Плохо: вызов метода внутри цикла
for (int i = 0; i< 1000000; i++) {
    String str = getString(i);
    // ...
}

// Хорошо: минимизация вызовов методов в цикле
for (int i = 0; i < 1000000; i++) {
    String str = "String " + i;
    // ...
}
These were just a few simple Java tricks that can improve your productivity. Keep in mind that optimizing performance can be challenging, and a developer will often need to analyze their code to identify performance bottlenecks.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION