Collections Framework - List, Set, Map.
Collections Framework - List, Set, Map.
List preserves the insertion order, it allows positional access and insertion
of elements.
}
}
}
import java.util.*;
public class GFG {
// Creating a List
List<String> al = new ArrayList<>();
mango
// Adding elements in the List orange
al.add("mango");
al.add("orange"); Grapes
al.add("Grapes");
class Main {
class SetCollection {
public static void main(String[] args) {
Set<String> hSet = new HashSet<>();
hSet.add("A");
hSet.add("B");
hSet.add("C"); List contains B? : true
Is list empty or not:false
System.out.println("List contains B? : " + hSet.contains("B"));
Elements of hashset: A
hSet.remove("C"); B
System.out.println("Is list empty or not:" + hSet.isEmpty());
System.out.print("Elements of hashset: ");
Iterator<String> it = hSet.iterator();
while (it.hasNext()) {
System.out.print(it.next() + "\t");
}
System.out.println(); }}
import java.util.*;
import java.lang.*;
import java.io.*;
class SetCollection {
public static void main(String[] args) {
LinkedHashSet<String> lhSet = new LinkedHashSet<>();
lhSet.add("E");
lhSet.add("F");
//It will not add E again as it is already present.
Hashcode for set:139
lhSet.add("E"); Tset represented in sorted
System.out.println("Hashcode for set:" + lhSet.hashCode()); form:[H, I, L]
First vaue of tSet:H
// ------> TreeSet <------ Last vaue of tSet:Y
TreeSet<String> tSet = new TreeSet<>();
tSet.add("L");
tSet.add("I");
tSet.add("H");
System.out.println("Tset represented in sorted form:" + tSet);
tSet.add("Y");
System.out.println("First vaue of tSet:" + tSet.first());
System.out.println("Last vaue of tSet:" + tSet.last()); } }
import java.util.*;
// Main class
class GFG {
// Main driver method
public static void main(String args[])
{ // Creating an empty HashMap
Map<String, Integer> hm = new HashMap<String, Integer>();
// Inserting pairs in above Map
// using put() method a:100
hm.put("a", new Integer(100));
hm.put("b", new Integer(200)); b:200
hm.put("c", new Integer(300)); c:300
hm.put("d", new Integer(400));
d:400
// Traversing through Map using for-each loop
for (Map.Entry<String, Integer> me :
hm.entrySet()) {
// Printing keys
System.out.print(me.getKey() + ":");
System.out.println(me.getValue()); } } }