umma.dev

Learning Java: Part Four

In the last part of this series, I explore Java’s built-in data structures.

ArrayLists

You must import java.until.ArrayList at the top of your program.

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

days.add("Monday");
days.add("Tuesday");

// adding values to a specified index
days.add(3, "Wednesday");

System.out.println(days.get(0)); // Monday

days.remove("Wednesday");
days.remove(0); // remove the value in index zero

LinkedLists

You must import java.util.LinkedList at the top of your program.

LinkedList<String> days = new LinkedList<String>();

days.add("Monday");
days.add("Tuesday");

days.add(3, "Wednesday");

System.out.println(days.get(0)); // Monday

days.remove("Tuesday");
days.remove(0);
days.remove(); // removes first element in linkedlist

HashMaps

Reminder: A hashmap stores a collection of key-value pairs, in which each key is a unique identifier for the associated value.

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

fruit.put("strawberries", 10);
fruits.put("pears", 4);
fruits.put("oranges", 2);
frits.put("apples", 6);

fruits.remove("oranges");

System.out.println(fruits.get("pears")); // 4

System.out.println(fruit.size()); // 3

for(String key : fruit.keySet()) {
  System.out.println("Key: " + key + ", Value: " + fruit.get(key));
}

/*
  Key: strawberries, Value: 10
  Key: oranges, Value: 2
  Key: apples, Value: 6
*/

Sets

Set<String> days = new HashSet<String>()

days.add("Monday");
days.add("Tuesday");
days.add("Wednesday");

days.remove("Wednesday");

System.out.println(days.contains("Wednesday")); // false

System.out.println(days.size()); // 2

for(String item: days) {
  System.outprintln(item);
}

/*
  Monday
  Tuesday
*/