Spaces:
Running
Running
File size: 2,773 Bytes
b4c9a50 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | 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.
|