Presentation is loading. Please wait.

Presentation is loading. Please wait.

(4th edition: Chapter 12, Interlude 5)

Similar presentations


Presentation on theme: "(4th edition: Chapter 12, Interlude 5)"— Presentation transcript:

1 (4th edition: Chapter 12, Interlude 5)
Lists in Java (4th edition: Chapter 12, Interlude 5) Chapter 10, Interlude 4 Java-8 List Streams

2 Outline Review of Lists, ArrayLists, LinkedLists, and ListIterators
Creating lists that can’t be changed Using List streams to build and reduce Lists

3 Lists are for Listing Things
What do you want to do with a list? add stuff to it print it out look to see what’s on it check how long it is check if some particular thing’s on it remove stuff from it List interface has methods for all those and lots more!

4 List ADT and Interface What is a list?
sequence of things, all the same type (1st item, 2nd item, 3rd item, ..., last item) java.util.List interface is parameterized say what kind of objects are allowed on it list of Strings: List<String> myWords; list of Files: List<File> myFiles; list of integers: List<Integer> myNumbers; NOTE: List<int> is not allowed

5 List Data Types List is an interface Two kinds of List objects
OK for variables List<String> var; but not for objects var = new List<String>(); Two kinds of List objects ArrayList var = new ArrayList<String>(); LinkedList var = new LinkedList<String>(); used exactly the same way! choose depending on what needs doing both from java.util

6 Side-by-Side List<String> list; list = new ArrayList<String>(); list.add("ten"); list.add("twenty"); list.add("thirty"); System.out.println(list); list.remove("twenty"); List<String> list; list = new LinkedList<String>(); list.add("ten"); list.add("twenty"); list.add("thirty"); System.out.println(list); list.remove("twenty"); [ten, twenty, thirty] [ten, thirty] [ten, twenty, thirty] [ten, thirty]

7 Creating a List and Adding to it
Normal variable + new object declaration List<String> myWords = new ArrayList<String>(); List starts out empty Add method to add items (to end of list) myWords.add("Ten"); myWords.add("Twenty"); can also say where to add to the list myWords.add(1, "Fifteen"); skip over 1 item, then add “Fifteen” "Ten", "Fifteen", "Twenty" myWords "Ten", "Twenty" myWords myWords "Ten" myWords

8 List Objects Grow List objects start empty
not like array objects array has a length when you create it array elements are initialized (to 0 if nothing else) Will grow as long as you keep adding that’s its length as long as it exists

9 Printing Out a List Lists can be printed directly!
System.out (to screen) or a PrintWriter (to file) System.out.println("The list is " + myWords + "."); Output just like Arrays.toString(…) elements printed using their toString method The list is [Ten, Fifteen, Twenty].

10 Getting List Elements Lists use zero-based indexing just like arrays
String firstWord = myWords.get(0); System.out.println("The first word is " + firstWord + "."); "Ten", "Fifteen", "Twenty" myWords "Ten" firstWord The list is [Ten, Fifteen, Twenty]. The first word is Ten.

11 Checking its Length Method called size instead of length
not like arrays int size = myWords.size(); System.out.println("Last is " + myWords.get(size-1) + "."); "Ten", "Fifteen", "Twenty" myWords 3 size The list is [Ten, Fifteen, Twenty]. The first word is Ten. Last is Twenty.

12 Looking for Particular Items
Is it there at all? contains Where exactly is it? indexOf if (myWords.contains("Twenty")) { System.out.println("We have a Twenty!"); System.out.println("It’s at location " + myWords.indexOf("Twenty") + "."); } We have a Twenty! It’s at location 2.

13 Looking for Particular Items
Is it there at all? contains Where exactly is it? indexOf if (myWords.contains("Hundred")) { System.out.println("We have a Hundred!"); } System.out.println("The location of the Hundred is " + myWords.indexOf("Hundred") + "."); We have a Twenty! It’s at location 2. The location of the Hundred is -1.

14 Removing Stuff What thing to remove, or which position?
int argument  remove from that position myWords.remove(1); System.out.println(myWords); object argument  remove that object myWords.remove("Ten"); [Ten, Twenty] [Twenty]

15 Standard Loops for Lists
Multiple ways to loop thru a list can use the usual for loop for (int i = 0; i < myWords.size(); i++) can use this simplified for loop (for-each loop) for (String word : myWords) They work if you’re just looking at the list can cause trouble if you’re adding or removing from the list at the same time!

16 Usual for Loop for (int i = 0; i < allMyWords.size(); i++) { System.out.println("\t" + i + ") " + allMyWords.get(i)); } "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords 0) Ten 1) Fifteen 2) Twenty 3) Thirty 4) Fifty

17 Simplified for Loop for (String word : allMyWords) { System.out.println("\t" + word); } "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords Ten Fifteen Twenty Thirty Fifty

18 Exercise Write a code fragment that reads a single line of words and adds them all to a List, then prints out the list Enter a line of words below: This is the line of words I entered. The words you entered were: [This, is, the, line, of, words, I, entered.]

19 Exercise Make this program using Lists N heats; top 2 advance
What order did they finish in heat 1? Jill Anne Leslie Freida What order did they finish in heat 2? Carol Louisa Judith Annette What order did they finish in heat 3? Carla Giselle Lois Rachel What order did they finish in heat 4? Yvonne Darla Brenda The people who advanced are: [Jill, Anne, Carol, Louisa, Carla, Giselle, Yvonne, Darla] Not advancing were: [Leslie, Freida, Judith, Annette, Lois, Rachel, Brenda]

20 List Iterators To add or remove items while looping
List Iterator goes thru list one item at a time like a Scanner going thru a file: next and hasNext can remove the item you just looked at can add item beside the one you just looked at Can also use it for changing items or just to look at the items

21 Creating a List Iterator
Parameterized, just like List & ArrayList just ask the list for one ListIterator<String> it = allMyWords.listIterator(); no “new ListIterator<String>()” type needs to be the same as the List’s type "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords & it

22 Looping thru the List hasNext: is there is another item?
next: get the next item (and advance) while (it.hasNext()) { System.out.println(it.next()); } Ten Fifteen Twenty Thirty Fifty "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords & it

23 Removing with an Iterator
Delete items that start with “F” while (it.hasNext()) { String word = it.next(); if (word.startsWith("F")) it.remove(); } "Thirty" word "Fifty" word "Twenty" word "Ten" word "Fifteen" word "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords & it

24 ListIterators Can Go in Reverse
Start at the last element give listIterator method length of list use previous & hasPrevious public static void writeListReversed(List<String> list) { ListIterator<String> it = list.listIterator(list.size()); while(it.hasPrevious()) { System.out.println("\t" + it.previous()) } not as clumsy as the for loop version

25 Removing with an Iterator
Going backwards is the same! while (it.hasPrevious()) { String word = it.previous(); if (word.startsWith("F")) it.remove(); } "Fifteen" word "Ten" word "Twenty" word "Fifty" word "Thirty" word "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords & it

26 Removing with an Iterator
Which item did you just look at? That’s the one that gets removed. General policy check to see if there is a next/previous save the next/previous into a variable check the variable to see if it needs removed if so, use the iterator’s remove method to remove it

27 Changing with an Iterator
Same as removing but we’re just changing instead of removing General policy check to see if there is a next/previous save the next/previous into a variable check the variable to see if it needs changed if so, use the iterator’s set method to change it

28 Changing with an Iterator
Change words starting with F to upper case! while (it.hasPrevious()) { String word = it.previous(); if (word.startsWith("F")) it.set(word.toUpperCase()); } "Fifty" word "Thirty" word "Ten" word "Fifteen" word "Twenty" word "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" allMyWords "FIFTEEN", "FIFTY" & it

29 Adding with an Iterator
Adds towards the front of the list if going forward, then iterator will not see them if going backward. iterator will see them "Ten", "A", "Fifteen", "Twenty", "Thirty", "Fifty" "Ten", "A", "B", "Fifteen", "Twenty", "Thirty", "Fifty" "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" & it "Ten", "Fifteen", "Twenty", "Thirty", "A", "Fifty" "Ten", "Fifteen", "Twenty", "Thirty", "B", "A", "Fifty" "Ten", "Fifteen", "Twenty", "Thirty", "Fifty" & it

30 Exercise Use an iterator to go thru a List<Integer>, removing every negative number and changing every 0 to a 42 go from front to back How would it change if we wanted to go from back to front?

31 List Interface More List interface methods
isEmpty() check if list is empty clear() make list empty addAll(otherList) add all these containsAll(otherList) check if contains these removeAll(otherList) remove all these retainAll(otherList) keep only these subList(from, to) get part of the list

32 Getting Parts of Lists Choose first element of list (by position), and first element not on the list (by position) List<String> letters = new ArrayList<>(); letters.add("b"); letters.add("i"); letters.add("e"); letters.add("y"); letters.add("o"); S.o.p("Letters: " + letters); S.o.p("Letters 1 to 3:" + letters.subList(1, 3)); Letters: [b, i, e, y, o] Letters 1 to 3: [i, e]

33 Sublists Actually part of the larger list (not a copy)
Select part of the list [b, i, e, y, o] letters.subList(1, 3)  [i, e] Actually part of the larger list (not a copy) can be used to modify parts of the list letters.subList(1, 3).set(1, "x"); [b, i, x, y, o] letters.subList(1, 3).clear(); [b, y, o] b i e y o 1 2 3 4 5 1 2 b i e x y o 1 2 3 4 5

34 Exercise A card game; start list with four cards
top four cards of deck if top has same rank as 3rd down, remove all four if top has same suit as 3rd down, remove middle two add next card on top play until list is empty or no cards to be added K♥ 7♦ 5♠ K♦ 9♥ 5♦ 8♠ 8♣ Q♥ 2♦ 7♥

35 Arrays.asList Can initialize an array quickly:
String[] arr = {"to", "be", "or", "not"}; Can do similar thing for Lists List<String> arrList = Arrays.asList(arr); List<String> list = Arrays.asList("to", "be", "limited"); Must be List; not ArrayList ArrayList<String> wordList = Arrays.asList("oh"); not a LinkedList, either

36 Arrays.asList Fixed Length
Creates a List containing the given elements List<String> list = Arrays.asList("to", "be", "limited"); The List is fixed length: list.remove("limited"); // compiler doesn’t complain list.add("unlimited"); // compiler doesn’t complain both throw UnsupportedOperationException You can use other List operations, however list.set(2, "semi-limited"); // changes third word

37 Arrays.asList and Primitives
Cannot use primitive array in asList int[] intArr = {1, 3, 5, 7}; List<Integer> noGood = Arrays.asList(intArr); Can use primitive values in asList List<Integer> intList = Arrays.asList(2, 4, 6, 8); Can use wrapper class array Integer[] intWrapArr = {1, 3, 5, 7}; List<Integer> okList = Arrays.asList(intWrapArr);

38 asList and the Underlying Array
asList uses the given array String[] arr = {"to", "be", "or", "not", "to", "be"}; List<String> list = Arrays.asList(arr); arr[2] = "our"; list.set(3, "knot"); System.out.println(Arrays.toString(arr)); System.out.println(list); [to, be, our, knot, to, be]

39 Truly Unmodifiable Lists
As of Java 9: List.of(…) creates a List that cannot be modified always contains same elements in same order List<Integer> fivePrimes = List.of(2, 3, 5, 7, 11); rejects any attempt at change throws UnsupportedOperationException except: objects in the list may be mutable immutableListOfColours.get(5).setRed(0);

40 List.of and Primitives Can pass an array to List.of
String[] arr = {"to", "be"}; List<String> list = List.of(arr); Cannot pass an array of primitives int[] arr = {1, 2, 3}; List<Integer> list = List.of(arr); Arrays of wrapper classes OK

41 Another Unmodifiable List
Collections.unmodifiableList(someList) not a copy it’s a view—a way of looking at the List prevents any changes throws UnsupportedOperationException & someList someList.add("Delta"); & view Alpha Bravo Charlie Delta view.set(1, "Beta"); UnsupportedOperationException

42 Unmodifiable List for Getters
Data type with List as instance variable private List<Course> coursesTaken; Returning a List breaks encapsulation client can add/remove/change elements Can return a copy (expensive) return new ArrayList<>(coursesTaken); // copy Or an unmodifiable List (cheap) return Collections.unmodifiableList(coursesTaken);

43 of vs asList vs Unmodifiable
List.of is for Lists of constants the elements never change List.of(someArray) copies array elements Arrays.asList is for wrapping arrays length never changes; elements may change elements not copied Collections.unmodifiableList is for protection wrap a List to prevent others from changing it

44 Lists and Loops Already know three ways to loop a List Different uses:
for (int i = 0; i < list.size(); ++i) { … } for (T element : list) { … } while (listIterator.hasNext()) { … } Different uses: for (int)  viewing/setting elements for (T)  viewing elements while (ListIterator)  add/remove/set elements

45 One More Way Can use a stream to go thru a List Can do it; Don’t do it
myList.stream() add method calls to do things myList.stream().forEach(t -> System.out.println(t)); prints each element of the list for each element in the list, print it out Can do it; Don’t do it not when you can write a simple for loop!

46 List Streams for Building Lists
Make a new list from an old list List<String> fWords = words.stream() .filter(t -> t.toUpperCase().startsWith("F")) .collect(Collectors.toList()); same as: List<String> fWords = new ArrayList<>(); for (String word : words) { if (word.toUpperCase.startsWith("F")) { fWords.add(word); }

47 List Stream Filters Filter method takes a Predicate<T>
t -> logicalExpression(t) for each element t in the stream: if logicalExpression(t) is true, t is kept if logicalExpression(t) is false, t is skipped Leaves you with a smaller stream can apply more filters, if you want List<Integer> smallEven = myList.stream() .filter(t -> t < 20) .filter(t -> t % 2 == 0) .collect(Collector.toList());

48 List Stream Collectors
Collect puts stream elements together argument is a collector various examples found in Collector class toList() turns stream into a List toSet() turns stream into a Set joining() turns stream into a single String joining(", ") puts ", " between elements joining(", ", "[", "]") adds "[" at start and "]" at end List’s toString method does this: myList.stream().collect(Collector.joining(", ", "[", "]"))

49 Mapping a List Stream Map replaces stream elements
replace each number with its squared value List<Integer> squares = numbers.stream() .map(n -> n * n).collect(Collectors.toList()); Map takes a Function<T, R> (from T to R) takes one value and returns another Java can figure out what T and R are replace each word with its uppercase version .map(s -> s.toUpperCase())

50 Reducing a Stream to a Value
As opposed to collecting them Reduce combines multiple values into one takes a starting value, and a BinaryOperator int sum = numbers.stream().reduce(0, (a, b) -> (a + b)); if the list is empty, sum will be zero; otherwise, it will be the sum of all numbers’ elements

51 Naming Methods to Use Lambda expressions can be replaced by method references t -> System.out.println(t)  System.out::println object.methodName(t)  object::methodName t -> t.toUpperCase()  String::toUpperCase t.methodName()  Class::methodName Wrapper classes have some useful methods (a, b) -> (a + b)  Integer::sum (for integers) (a, b) -> (a + b)  Double::sum (for doubles)

52 Using List Streams Start with the List object
add .stream() add .filter and/or .map methods as many as you like add .collect or .reduce one or the other; not both! Save result in an appropriate variable the original List object will not be modified!

53 Exercise Write a single line of code to find the sum of the squares of all the odd numbers in the List<Integer> myNumbers e.g. [1, 4, 3, 8]    10

54 Questions


Download ppt "(4th edition: Chapter 12, Interlude 5)"

Similar presentations


Ads by Google