Collections in java

 Collections in java


Collections are a set of interfaces and classes in Java that allow developers to store, manipulate, and retrieve collections of objects. Here is an example of how to use some of the collection classes in Java:



import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;


public class Main {

  public static void main(String[] args) {

    List<String> fruits = new ArrayList<>();

    fruits.add("apple");

    fruits.add("banana");

    fruits.add("orange");


    Map<String, Integer> prices = new HashMap<>();

    prices.put("apple", 1);

    prices.put("banana", 2);

    prices.put("orange", 3);


    for (String fruit : fruits) {

      System.out.println(fruit + " costs " + prices.get(fruit) + " dollars");

    }

  }

}

In this example, we define a list of strings called fruits. We then define a map that associates each fruit with a price. We use a for loop to iterate over the fruits list, and for each fruit, we use the prices.get method to retrieve the price from the prices map. We then print a message to the console that includes the fruit and its price.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...