In Java, both Set
and Map
are interfaces that are part of the Java Collections Framework.
A
TweetSet
is an unordered collection of unique elements, meaning that it cannot contain duplicate elements. Some common implementations of theSet
interface includeHashSet
,LinkedHashSet
, andTreeSet
. Here’s an example of how to create aHashSet
:
Set<String> mySet = new HashSet<String>();
A Map
, on the other hand, is a collection of key-value pairs, where each key is associated with a corresponding value. The keys must be unique, but the values can be duplicated. Some common implementations of the Map
interface include HashMap
, LinkedHashMap
, and TreeMap
. Here’s an example of how to create a HashMap
:
Map<String, Integer> myMap = new HashMap<String, Integer>();
Here’s an example of how to add elements to a Set
and a Map
:
Set<String> mySet = new HashSet<String>();
mySet.add("apple");
mySet.add("banana");
mySet.add("orange");
Map<String, Integer> myMap = new HashMap<String, Integer>();
myMap.put("apple", 1);
myMap.put("banana", 2);
myMap.put("orange", 3);
To access the elements in a
TweetSet
or aMap
, you can use methods likecontains
orget
:
if (mySet.contains("apple")) {
System.out.println("The set contains an apple");
}
int value = myMap.get("banana");
System.out.println("The value associated with 'banana' is " + value);
Note that there are many more methods available for Set
and Map
that allow you to manipulate and query the collections in various ways.