Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Populating Elements in Java Collections

Tech 1

The java.util.Collections class is a utility class within Java’s collection framework that provides static methods for working with collections, but it cannot be instantiated to populate collections directly. To add elements to a collection, you will typically use methods from concrete collection implementations like ArrayList, HashSet, or others.

A basic example of populating a ArrayList using its built-in add() method:

import java.util.ArrayList;
import java.util.Collections;

public class CollectionPopulationDemo {
    public static void main(String[] args) {
        ArrayList<String> fruitList = new ArrayList<>();
        
        fruitList.add("Banana");
        fruitList.add("Apple");
        fruitList.add("Cherry");
        
        System.out.println("Original list: " + fruitList);
        Collections.sort(fruitList);
        System.out.println("Sorted list: " + fruitList);
    }
}

In this snippet, we first initialize an empty ArrayList for string values, then add three fruit names using add(). We then sort the list with Collections.sort() and print both the original and sorted results.

To streamline adding multiple elements to a collection, you can use Collections.addAll(), which accepts a target collection and a variable number of elements to add:

import java.util.ArrayList;
import java.util.Collections;

public class CollectionsAddAllDemo {
    public static void main(String[] args) {
        ArrayList<String> colorList = new ArrayList<>();
        Collections.addAll(colorList, "Crimson", "Azure", "Lime");
        System.out.println("Populated color list: " + colorList);
    }
}

This approach reduces boilerplate code compared to calling add() repeatedly for each individual element.

Java 8 and Later Stream API Population

Java 8 introduced the Stream API, which enables declarative population and transformation of collections without verbose looping code.

To generate a populated list with computed values, use IntStream to create a sequence of numbers, transform them, and collect the results into a list:

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class StreamPopulationDemo {
    public static void main(String[] args) {
        List<Integer> multipliedList = IntStream.range(0, 6)
                                               .map(num -> num * 3)
                                               .boxed()
                                               .collect(Collectors.toList());
        System.out.println("Computed list: " + multipliedList);
    }
}

Here, IntStream.range(0,6) creates a stream of integers from 0 to 5. The map() method multiplies each value by 3, boxed() converts the primitive int values to wrapper Integer objects, and collect(Collectors.toList()) assembles the stream into a standard List instance.

To create a fixed-size list with identical values, map each stream element to a constant value:

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ConstantValueListDemo {
    public static void main(String[] args) {
        List<Integer> constantList = IntStream.range(0, 4)
                                             .mapToObj(idx -> 25)
                                             .collect(Collectors.toList());
        System.out.println("Constant value list: " + constantList);
    }
}

This code generates a list of four elements, all set to the integer 25.

For populating missing values in an existing collection, you can iterate over the collection’s indices with a stream and replace null or empty entries:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class FillMissingValuesDemo {
    public static void main(String[] args) {
        List<Integer> rawList = new ArrayList<>();
        rawList.add(7);
        rawList.add(null);
        rawList.add(14);
        rawList.add(null);
        
        List<Integer> fixedList = IntStream.range(0, rawList.size())
                                          .mapToObj(idx -> rawList.get(idx) != null ? rawList.get(idx) : idx * 4)
                                          .collect(Collectors.toList());
        System.out.println("Fixed list with replaced nulls: " + fixedList);
    }
}
Tags: Java

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.