Spaces:
Running
Running
TurkuBasicOOPinJava / Week 7: Enum, Generic Type, Streams, write to file, class diagram /11B. Sentences Ending with a Period
| Write a method: | |
| public static ArrayList<String> sentencesWithPeriod(ArrayList<String> sentences) | |
| that takes a list of sentences as strings as its parameter. | |
| The method returns a new list containing only those sentences from the original list that end with a period. | |
| Use 'stream' for your solution | |
| import java.util.Random; | |
| import java.util.ArrayList; | |
| import java.util.stream.Collectors; | |
| public class Test { | |
| public static void main(String[] args) { | |
| final Random r = new Random(); | |
| String[] sub = "Pike Perch Roach Rose Poppy Lily Rabbit Bunny Hare Java Python".split(" "); | |
| String[] ob = "fish flower plant animal mammal programming language".split(" "); | |
| ArrayList<String> sentences = new ArrayList<>(); | |
| int m = r.nextInt(6) + 6; | |
| for (int i = 0; i < m; i++) { | |
| String sentence = sub[r.nextInt(sub.length)] + " is a " + ob[r.nextInt(ob.length)]; | |
| sentence += r.nextInt(2) == 0 ? "." : ""; | |
| sentences.add(sentence); | |
| } | |
| System.out.println("Sentences:"); | |
| sentences.stream().forEach(s -> System.out.println("" + s)); | |
| System.out.println("Sentences ending with a period:"); | |
| sentencesWithPeriod(sentences).stream().forEach(s -> System.out.println(s)); | |
| } | |
| //ADD | |
| public static ArrayList<String> sentencesWithPeriod(ArrayList<String> sentences) { | |
| // approach 1 - substring | |
| // substring() returns a new string | |
| // => which is a reference type object | |
| // => so compare using .equals() | |
| //https://stackoverflow.com/questions/5163785/how-do-i-get-the-last-character-of-a-string | |
| return sentences.stream(). | |
| filter(str -> str.substring(str.length() - 1).equals(".")). | |
| collect(Collectors.toCollection(ArrayList::new)); | |
| // approach 2 - charAt | |
| // charAt() returns a char | |
| // => which is a primitive type | |
| // => so compare using '==' | |
| return sentences.stream(). | |
| filter(str -> str.charAt(str.length() - 1) == '.'). | |
| collect(Collectors.toCollection(ArrayList::new)); | |
| // approach 3 - endsWith | |
| // endsWith() returns a boolean | |
| // => naturally 'true' elements are kept | |
| return sentences.stream(). | |
| filter(str -> str.endsWith(".")). | |
| collect(Collectors.toCollection(ArrayList::new)); | |
| } | |
| } | |
| Sentences: | |
| Bunny is a programming. | |
| Pike is a plant. | |
| Bunny is a mammal | |
| Java is a flower | |
| Hare is a animal | |
| Lily is a programming. | |
| Sentences ending with a period: | |
| Bunny is a programming. | |
| Pike is a plant. | |
| Lily is a programming. | |