Learn - Collection - List, Set & Map in Java
Collection is an Interface in Java
1.
Single dimensional – List & Set Interfaces
2.
Multi-dimensional – Map Interface
A Java collection framework
provides an architecture to store and manipulate a group of objects. A Java
collection framework includes the following:
·
Interfaces
·
Classes
·
Algorithm
Interfaces: Interface in Java refers
to the abstract data types. They allow Java collections to be manipulated
independently from the details of their representation. Also, they form a
hierarchy in object-oriented programming languages.
Classes: Classes in Java are the
implementation of the collection interface. It basically refers to the data
structures that are used again and again.
Algorithm: Algorithm refers to the
methods which are used to perform operations such as searching and sorting, on
objects that implement collection interfaces. Algorithms are polymorphic in
nature as the same method can be used to take many forms or you can say perform
different implementations of the Java collection interface.
Collection in java is a container
object i.e., holding multiple objects either homogeneous or heterogeneous,
unique & Duplicate as a single unit without size limitations with a single
name.
Used for storing multiple objects
as a single group & then Used for sending all the objects stored as a
single group, at a time from one class method to another class method by
passing it as a method parameter argument.
1. Its used to group
homogeneous/heterogeneous objects without size limitations
2. Used for carrying multiple
objects at a time from one application to another among muliple layers of MVC
architecture as method arguments & return types.
When should we use Collection:
If we want to send multiple objects
by containing them in a single object as a single parameter argument
or if we want to return
multiple values from a method as a single return type value,we need to use
collection.
Various ways to collect objects:
1. In collection format
-->object will have no identity.
2. In (key,Value) pair format
-Map-->Object will have identity.
In Collection Framework all the classes are classified
into 3 categories:
Problems with Collection:
1. Not Type-Safe to use
2. Require type casting, while
retrieving
Solution: Generics
1. Provides Type-Safety for
Collections
2. Resolves Type-Casting problem
Bounded & Unbounded types
Class Test<T>
{
//Unbounded Type example
}
Class Test<T extends X>
{
//Bounded Type example, where X is
a Class or Interface
}
So, as a Type parameter will
bound/restrict the user from adding object types other than X type or its
child/implementing classes.
Example:
Class Test<T extends Number>
{
//Bounded to add only objects of
type Number & its child classes.
}
Container objects
meant for storing objects - it's
an object that can store other objects
The below 4 Interfaces & their sub classes.
1. List
2. Set
3. Map
4. Queue
Cursor objects
meant for retrieving objects
1. Enumeration
2. Iterator
3. ListIterator
Utility objects
Class given to perform various
operations on container objects.
1. Collections
2. Arrays
List
1.
Maintains insertion order
2.
Store data having duplicate values
3.
Implementation Class à ArrayList, LinkedList, etc
a.
List<String> values = new ArrayList<String>()
4.
Create a List from another List
a.
List<String> values = new ArrayList<String>(values2)
5.
Create a List from Set
a.
List<String> values = new ArrayList<String>(Set
reference variable)
6.
Add values to a List
a.
values.add(“Ajay”)
b.
values.add(index, “Ajay”)
7.
Get the length
a.
values.size()
8.
Get value at index
a.
values.get(index)
9.
Remove value
a.
values.remove(index)
b.
values.remove(“Ajay”)
10.
Remove all values
a.
values.clear()
b.
values.removeAll()
11.
Sort & Reverse
a.
Collections.sort(values)
b.
Collections.reverse(values)
12.
Compare 2 Collections & remove or retain
matching elements
a.
values2.removeAll(values)
b.
values2.retainAll(values)
Program to Sort
Using Collection
package week3.day1;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class SortUsingCollections {
public static void main(String[] args) {
// Declare a String array and add the
Strings values as (HCL, Wipro,
Aspire Systems, CTS)
String[] values = { "HCL", "Wipro", "Aspire Systems", "CTS" };
// get the length of the array
int length = values.length;
// sort the array
List<String> valueList = Arrays.asList(values);
// Iterate it in the reverse order
Collections.sort(valueList);
Collections.reverse(valueList);
// print the array
System.out.println(valueList);
// Required Output: Wipro, HCL ,
CTS, Aspire Systems
}
}
Set
1.
Duplicates are not allowed à verifies if the
element is already inserted, if true – it skips that one.
a.
Eg – Set<String> values = new
HashSet<String>() //implementation object
i.
values.add(“Ajay”) Ã Returns true
ii.
values.add(“Ajay”) Ã Returns false //doesn’t allow
duplicates
2.
Implementation Class à HashSet, LinkedHashSet, TreeSet
3.
May or may not maintain the insertion order – it
depends upon the Implementation Class
a.
HashSet Ã
doesn’t maintain insertion order, uses Hashing algorithm, Execution is much
faster as it stores in random order
i.
Set<E> values = new HashSet<E>()
b.
LinkedHashSet Ã
Maintains Insertion order
i.
Set<E> values = new LinkedHashSet <E>()
c.
TreeSet Ã
Maintains Ascii order
i.
Set<E> values = new TreeSet <E>()
4.
Set doesn’t contain get method
a.
Create a List from Set
i.
List<String> values1 = new ArrayList<String>(values)
Program to Remove Duplicate Characters using LinkedHashSet
//Insertion order is maintained
package week3.day1;
import java.util.LinkedHashSet;
import java.util.Set;
public class RemoveDuplicates {
// Input
--> Agilysys India
// Expected
--> glnd
public static void main(String[] args) {
String input = "Agilysys India";
char[] charArray = input.toUpperCase().toCharArray();
Set<Character> values = new LinkedHashSet<Character>();
// Interface InterfaceReference = new
ImplementationClass();
Set<Character> dupValues = new LinkedHashSet<Character>();
for (char indChar : charArray) {
if (!values.add(indChar)) {
dupValues.add(indChar);
}
/*
if (values.contains(indChar)) {
dupValues.add(indChar); } else {
values.add(indChar); }
*/
//System.out.println("Main
"+values.toString());
//System.out.println("Duplicate
"+dupValues.toString());
}
values.removeAll(dupValues);
//System.out.println(values.toString());
for (Character eachChar : values) {
if (Character.isSpace(eachChar) //
if(eachChar!=' ')
{
} else {
System.out.print(eachChar);
}
}
}
}
Program to Remove
Duplicate Characters using HashSet
//Random Insertion order
package week3.day1;
import java.util.HashSet;
import java.util.Set;
public class RemoveDuplicates {
public static void main(String[] args) {
String input = "Agilysys India";
char[] charArray = input.toUpperCase().toCharArray();
Set<Character> values = new HashSet<Character>();
// Interface InterfaceReference = new
ImplementationClass();
Set<Character> dupValues = new HashSet<Character>();
for (char indChar : charArray) {
if (!values.add(indChar)) {
dupValues.add(indChar);
}
}
values.removeAll(dupValues);
for (Character eachChar : values) {
if (Character.isSpace(eachChar))
{
} else {
System.out.print(eachChar);
}
}
}
}
Map Interface
Used for storing key value pairs
Linked HashMap:
Will retain the Entries in the insertion order.
HashMap:
Will not retain the Entries in the insertion order.
Methods in Map Interface:
public Object put(Object key,
Object value):
This method is used to insert an
entry in this map.
public void putAll(Map map):
This method is used to insert the
specified map in this map.
public Object remove(Object
key):
This method is used to delete an
entry for the specified key.
public Object get(Object key):
This method is used to return the
value for the specified key.
public boolean containsKey(Object
key):
This method is used to search the
specified key from this map.
public Set keySet():
This method is used to return the
Set view containing all the keys.
public Set entrySet():
The entrySet( ) method declared by
the Map interface returns a Set containing the map entries.
Each of these set elements is a
Map.Entry object.
Usually we use this to get the keys
and values from a map.
Map.Entry Interface
This describes an element (a
key/value pair) in a map. This is an inner class of Map.
The Map.Entry interface enables you
to work with a map entry.
Its used hold a single entry of key
value.
//obj.entrySet results in set
view of entries, where each entry of key-Value pair can be stored resulted can
be stored in Map.Entry
for (Map.Entry<String, Integer> entry : obj.entrySet())
//entry.getKey() will retrieve
the Key for that entry while iterating over the entrySet
// entry.getValue() will
retrieve the value for that entry while iterating over the entrySet
Linked HashMap Example:
Usage -> Will
retain the Entries in the insertion order. Example below will indicate the
usage
package collectPractise;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
public class
GetFirstNonRepeatedChar {
public static void main(String[] args) {
System.out
.println("First non repeated character for String
analogy is : "
+ getNonRepeatedCharacter("analogy"));
System.out
.println("First non repeated character for String
easiest is : "
+ getNonRepeatedCharacter("easiest"));
}
public static Character
getNonRepeatedCharacter(String str) {
Map<Character, Integer> countCharacters = new
LinkedHashMap<Character, Integer>();
for (int i = 0; i < str.length() - 1; i++) {
Character c = str.charAt(i);
if (!countCharacters.containsKey(c)) {
countCharacters.put(c, 1);
} else {
countCharacters.put(c, countCharacters.get(c) + 1);
}
}
// As LinkedHashMap maintains insertion order, first character
with
// count 1 should return first non repeated character
for (Entry<Character, Integer> e :
countCharacters.entrySet()) {
if (e.getValue() == 1)
return e.getKey();
}
return null;
}
}
Sample Examples:
Program 1:
// Program to add entries to a Map & iterate over it
package com.CollectionsPractice;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class Demo {
public static void main(String[] args) {
// Program to add entries to a Map & iterate over it
Map<String, Integer> obj = new HashMap<String,
Integer> ();
// Add Book details with Price of each
obj.put("Java Black book", 1500);
obj.put("Python Programming", 1200);
obj.put("Devops Complete Solution", 2500);
// return a set view of the mappings contained in this map
Set s = obj.entrySet();
// Call the iterator method on the Set view of mappings to iterate over
Iterator itr = s.iterator();
while (itr.hasNext()) {
// Retrieves entry by entry from the Map & stores in Entry ->
Individual Key & Value pairs
Map.Entry<String, Integer> entries = (Map.Entry<String,
Integer>) itr.next();
// result will be returned in a random order, as HasMap
doesn't maintain the order of insertion
System.out.println("" + entries.getKey() + ": " +
entries.getValue());
}
Output is as follows:
Devops Complete Solution: 2500
Java Black book: 1500
Python Programming: 1200
Program 1: Alternative
solution
// Program to add entries to a Map & iterate over it
package com.CollectionsPractice;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class Demo {
public static void main(String[] args) {
// Program to add entries to a Map &
iterate over it
Map<String, Integer> obj = new HashMap<String, Integer>();
// Add Book details with Price of each
obj.put("Java Black book", 1500);
obj.put("Python Programming", 1200);
obj.put("Devops Complete Solution", 2500);
//obj.entrySet results in set
view of entries, where each entry of key-Value pair can be stored resulted can
be stored in Map.Entry
for (Map.Entry<String, Integer> entry : obj.entrySet())
//entry.getKey() will
retrieve the Key for that entry while iterating over the entrySet
// entry.getValue() will
retrieve the value for that entry while iterating over the entrySet
System.out.println(entry.getKey() + ": " +
entry.getValue());
}
}
Program 2:
// Program to
find occurances of the characters within the string
package com.CollectionsPractice;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class Demo {
public static void main(String[] args) {
Map<Character, Integer> obj = new HashMap<>();
String s = "Program to print the count of each character in a
sentence";
for (int i = 0; i < s.length(); i++) {
char value = s.charAt(i);
if (Character.isAlphabetic(value)) {
if (obj.containsKey(value)) {
obj.put(value, obj.get(value) + 1);
} else {
obj.put(value, 1);
}
}
}
for (Map.Entry<Character, Integer> entry : obj.entrySet())
System.out.println(entry.getKey() + ": count equals " +
entry.getValue());
}
Output:
a: count equals 5
c: count equals 5
e: count equals 6
f: count equals 1
g: count equals 1
h: count equals 3
i: count equals 2
m: count equals 1
n: count equals 5
o: count equals 4
P: count equals 1
p: count equals 1
r: count equals 5
s: count equals 1
t: count equals 6
u: count equals 1
Comments
Post a Comment