The basic building blocks of programming - Lists and Loops
By The end of this lesson you should:
In this lesson we'll be meeting more of Java, and its syntax that corresponds to our pseudocode
We'll be meeting a few more aspects of programming, alongside some old ones:
A Collection is a data type that holds a bunch of another data type
Their type can be defined as:
CollectionType<TypeItContains> collectionOfSomething = ...
we will continue to use:
var collectionOfSomething = ...
An example creating some collections:
import java.util.List;
import java.util.Set;
import java.util.Map;
public class UsingCollections {
public static void main(String[] args) {
var listOfStrings = List.of("first element", "second element");
var setOfIntegers = Set.of(1, 2, 3);
var mapFromStringToBoolean = Map.of(
"this is true", true,
"this is false", false
);
}
}
Notice that we have to import these types, this is because they are not part of the core language.
Much like pseudocode says "for each item in the list", we can do this:
import java.util.List;
public class UsingForEach {
public static void main(String[] args) {
var alphabet = List.of("a", "b", "c");
for (var letter : alphabet) {
System.out.println(letter);
}
}
}
where "letter" is a name we chose for the current element in the list
Much like pseudocode says "for a counter from lower bound to upper bound", we can do this:
public class UsingForWithCounter {
public static void main(String[] args) {
for (var counter = 1; counter <= 10; counter = counter + 1) {
System.out.println("Number " + counter);
}
}
}
The "for a counter from lower bound to upper bound" code is made of 3 parts
for (var counter = 1; counter <= 10; counter = counter + 1) {
System.out.println("Number " + counter);
}
This is very similar to our pseudocode:
public class UsingWhile {
public static void main(String[] args) {
var condition = true;
while (condition) {
System.out.println("I'm stuck here forever");
}
}
}
This particular while-loop will run forever, because it contains no logic to set condition to false.