top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-
Writer's picturegeeta.thakur2008

Java Collections Part 2

Sort ArrayList

We have a sort() method in the Collections class. This class is is a part of java.util package. This method can be used to sort an ArrayList. In the following example we have sorted a list of String type alphabetically, however this method works on numeric list (such as Integer type ArrayList) as well.

import java.util.ArrayList;

import java.util.Collections;

public class JavaExample {

public static void main(String[] args) {

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

fruits.add("Orange");

fruits.add("Apple");

fruits.add("Banana");

fruits.add("Pineapple");

Collections.sort(fruits);

for (String str : fruits) {

System.out.println(str);

}

}

}

Output:

Methods of ArrayList class

In the above example we have used methods such as add() and remove(). However there are number of methods available which can be used directly using object of ArrayList class. Let’s discuss few important methods of ArrayList class.

1) add( Object o): This method adds an object o to the arraylist.

obj.add("hello");

This statement would add a string hello in the arraylist at last position.

2) add(int index, Object o): It adds the object o to the array list at the given index.

obj.add(2, "bye");

It will add the string bye to the 2nd index (3rd position as the array list starts with index 0) of array list.

3) remove(Object o): Removes the object o from the ArrayList.

obj.remove("Chaitanya");

This statement will remove the string “Chaitanya” from the ArrayList.

4) remove(int index): Removes element from a given index.

obj.remove(3);

It would remove the element of index 3 (4th element of the list – List starts with o).

5) set(int index, Object o): Used for updating an element. It replaces the element present at the specified index with the object o.

obj.set(2, "Tom");

It would replace the 3rd element (index =2 is 3rd element) with the value Tom.

6) int indexOf(Object o): Gives the index of the object o. If the element is not found in the list then this method returns the value -1.

int pos = obj.indexOf("Tom");

This would give the index (position) of the string Tom in the list.

7) Object get(int index): It returns the object of list which is present at the specified index.

String str= obj.get(2);

Function get would return the string stored at 3rd position (index 2) and would be assigned to the string “str”. We have stored the returned value in string variable because in our example we have defined the ArrayList is of String type. If you are having integer array list then the returned value should be stored in an integer variable.

8) int size(): It gives the size of the ArrayList – Number of elements of the list.

int numberofitems = obj.size();

9) boolean contains(Object o): It checks whether the given object o is present in the array list if its there then it returns true else it returns false.

obj.contains("Steve");

It would return true if the string “Steve” is present in the list else we would get false.

10) clear(): It is used for removing all the elements of the array list in one go. The below code will remove all the elements of ArrayList whose object is obj.

obj.clear();


HashMap in Java with Example

HashMap is a Map based collection class that is used for storing Key & value pairs, it is denoted as HashMap<Key, Value> or HashMap<K, V>. This class makes no guarantees as to the order of the map.

It is similar to the Hashtable class except that it is unsynchronized and permits nulls(null values and null key).

It is not an ordered collection which means it does not return the keys and values in the same order in which they have been inserted into the HashMap.

It does not sort the stored keys and Values. You must need to import java.util.HashMap or its super class in order to use the HashMap class and methods.


HashMap Example in Java:


In this example we have demonstrated almost all the important methods of HashMap class.

import java.util.HashMap;

import java.util.Map;

import java.util.Iterator;

import java.util.Set;

public class Details {

public static void main(String args[]) {

/* This is how to declare HashMap */

HashMap<Integer, String> hmap = new HashMap<Integer, String>();

/*Adding elements to HashMap*/

hmap.put(12, "Chaitanya");

hmap.put(2, "Rahul");

hmap.put(7, "Singh");

hmap.put(49, "Ajeet");

hmap.put(3, "Anuj");

/* Display content using Iterator*/

Set set = hmap.entrySet();

Iterator iterator = set.iterator();

while(iterator.hasNext()) {

Map.Entry mentry = (Map.Entry)iterator.next();

System.out.print("key is: "+ mentry.getKey() + " & Value is: ");

System.out.println(mentry.getValue());

}

/* Get values based on key*/

String var= hmap.get(2);

System.out.println("Value at index 2 is: "+var);

/* Remove values based on key*/

hmap.remove(3);

System.out.println("Map key and values after removal:");

Set set2 = hmap.entrySet();

Iterator iterator2 = set2.iterator();

while(iterator2.hasNext()) {

Map.Entry mentry2 = (Map.Entry)iterator2.next();

System.out.print("Key is: "+mentry2.getKey() + " & Value is: ");

System.out.println(mentry2.getValue());

}

}

}

Output:

key is: 49 & Value is: Ajeet

key is: 2 & Value is: Rahul

key is: 3 & Value is: Anuj

key is: 7 & Value is: Singh

key is: 12 & Value is: Chaitanya

Value at index 2 is: Rahul

Map key and values after removal:

Key is: 49 & Value is: Ajeet

Key is: 2 & Value is: Rahul

Key is: 7 & Value is: Singh

Key is: 12 & Value is: Chaitanya

HashMap Class Methods


Here is the list of methods available in HashMap class. I have also covered examples using these methods at the end of this post.

1. void clear(): It removes all the key and value pairs from the specified Map.

2. Object clone(): It returns a copy of all the mappings of a map and used for cloning them into another map.

3. boolean containsKey(Object key): It is a boolean function which returns true or false based on whether the specified key is found in the map.

4. boolean containsValue(Object Value): Similar to containsKey() method, however it looks for the specified value instead of key.

5. Value get(Object key): It returns the value for the specified key.

6. boolean isEmpty(): It checks whether the map is empty. If there are no key-value mapping present in the map then this function returns true else false.

7. Set keySet(): It returns the Set of the keys fetched from the map.

8. value put(Key k, Value v): Inserts key value mapping into the map. Used in the above example.

9. int size(): Returns the size of the map – Number of key-value mappings.

10. Collection values(): It returns a collection of values of map.

11. Value remove(Object key): It removes the key-value pair for the specified key. Used in the above example.

12. void putAll(Map m): Copies all the elements of a map to the another specified map.


Hope you liked it!!!


Happy Coding :)

22 views0 comments

Recent Posts

See All

BASIC JAVA

What is Java Java is a widely-used programming language for coding web applications. Java is a multi-platform, object-oriented, and...

コメント

5つ星のうち0と評価されています。
まだ評価がありません

評価を追加
bottom of page