Syntax Practice Flashcards
Write a loop that prints out every key in the Map foo.
for (char c : freq.keySet()) {
System.out.println(“key: “ + c);
}
Define a ListNode class
- It will have a public int value
- It will have a public ListNode next
- Define a constructor that sets the value
public class ListNode {
int val;
ListNode next;
ListNode (int val) {
this.val=val;
}
}
Get a value from a HashMap foo with the key ‘b’.
foo.get(‘b’);
Write an if statement that prints “Hello” if the Map foo contains the character ‘a’.
if (freq.containsKey(‘a’)) {
System.out.println(“Hello”);
Write a function “print” for an int array “foo.”
- The function should print out each value.
public static void print (int[] array) {
for (int item : array) {
System.out.print(item + “ - “);
}
}
Write a function “fibonacci”
- The function can be iterative
- The function will take in a size of the fibonacci seq
- The function will return a new array of the fibonacci seq for those values
public static int[] fibonacci (int size) {
int[] result = new int[size];
for (int i = 0; i < size; i++) {
if (i == 0 || i == 1) {
result[i] = i;
} else {
result[i] = result[i-1] + result[i-2];
}
}
return result;
}
Iterate over int array foo and set foo[i] = i + 1.
for (int i = 0; i < foo.length; i++) {
foo[i] = i + 1;
}
Write a function print
- The function can be static
- The function will take in an ListNode head
- The function will print out every value
public static void print (ListNode head) {
while (head != null) {
System.out.print(head.val + “ “);
head = head.next;
}
}
Write a function “sum”
- The function will take in an int array “arr”
- The function will return the sum of all values
public static int sum (int[] array) {
int result = 0;
for (int item : array) {
result += item;
}
return result;
}
Declare an int Stack foo.
Stack<Integer> foo = new Stack<>();</Integer>
- Write a function “getLength”
- The function can be static
- The function will take in a ListNode head
- The function will return the length of the LinkedList
public static int getLength (ListNode head) {
int length = 0;
while (head != null) {
length++;
head= head.next;
}
return length;
}
Declare a char -> int HashMap foo.
HashMap<Character,Integer> foo = new HashMap<>();
Insert a char-int key-value pair into a HashMap called foo.
foo.put(‘a’,3);
Write a loop that prints out every value in the Map foo.
for (char c : foo.keySet()) {
System.out.println(“value: “ + foo.get(c));
}
Declare a new array foo of type int and length 5.
int[] foo = new int[5];