-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJavaStreamPracticePrograms.txt
126 lines (123 loc) · 7.35 KB
/
JavaStreamPracticePrograms.txt
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
Topic: Given a list of Strings (this list contains blank and null elements), get a list of all the non-null strings
Example Source:
Input : ["foo", "", "bar"]
Result: ["FOO", "BAR"]
----------------------------------------
Topic: Creating a integer stream using range
https://stackoverflow.com/questions/57602096/convert-a-list-of-integers-into-a-comma-separated-string
Method 1: System.out.println(i.stream().map(String::valueOf)
.collect(Collectors.joining(",")));
Method 2: System.out.println(
IntStream.range(1, 6).boxed().map(String::valueOf)
.collect(Collectors.joining(","))
);
----------------------------------------
Topic: How to count the number of occurrences of an element in a List
https://stackoverflow.com/questions/505928/how-to-count-the-number-of-occurrences-of-an-element-in-a-list
----------------------------------------
Topic: Sorting a Map
Topic: Given a Map, we want a list output containing the keys in sorted order
For example, if the Map has key as person name and value as their age, then we want a list having the person name in sorted order
https://stackoverflow.com/questions/30425836/java-8-stream-map-to-list-of-keys-sorted-by-values
May be this also: https://stackoverflow.com/questions/53512537/java-stream-sort-map-by-key-and-value
List<Type> types = countByType.entrySet().stream()
.sorted(Comparator.comparing(Map.Entry::getValue))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
----------------------------------------
Topic: Sorting a Map (Level: Hard)
Requirement: /**
* Take a sentence as input and sort the words in it by the number of
* times they appear in the sentence. In the case of a tie, the words
* should be sorted alphabetically.
* V. IMP
* https://stackoverflow.com/questions/30425836/java-8-stream-map-to-list-of-keys-sorted-by-values
* https://stackoverflow.com/questions/53512537/java-stream-sort-map-by-key-and-value
*/
// Sort the entries in the map in reverse order of 'value' and if there is a tie, then the sort the entries based on the key in natural order and finally collect the keys in a list
My Code: E:\MyJava\IntellijProjects\collection-self-learn\src\main\java\org\example\puzzle\regex\SentenceAnalyser.java
My GitHub URL: TBD
----------------------------------------
Topic: Remove all punctuation marks from a given sentence
String replaceAll = sentence.replaceAll("[^a-zA-Z ]", "");
See my Trial: E:\MyJava\IntellijProjects\collection-self-learn\src\main\java\org\example\puzzle\regex\SentenceAnalyser.java
GitHub URL: TBD
----------------------------------------
Topic: Extract all the words from a sentence in an array
Topic: Count the number of words in a sentence
In the snippet code, we are taking into account that there might be multiple spaces between 2 words by using the regular expression while splitting.
//https://www.java67.com/2016/09/3-ways-to-count-words-in-java-string.html#:~:text=You%20can%20count%20words%20in,words%20in%20a%20given%20String.
public String[] getWordAsArray(String input) {
//Create Empty array
String[] strings = {};
if (input == null || input.isEmpty()) { return strings; }
strings = input.split("\\s+");
return strings;
// System.out.println("Count: " + strings.length);
}
----------------------------------------
Topic: Convert an array to a list
Topic: Convert an array to a List (resizable list)
Following will be a mutable list.
Method 1: List<String> wordList = new ArrayList<>(Arrays.asList(wordAsArray));
https://www.geeksforgeeks.org/conversion-of-array-to-arraylist-in-java/
Method 2: (UnmodifiableList)Arrays.asList(<ArrayObjectHere>)
String[] geeks = {"Rahul", "Utkarsh",
"Shubham", "Neelam"};
// Conversion of array to ArrayList
// using Arrays.asList
List al = Arrays.asList(geeks);
Since returned List is fixed-size List, we can’t add more element(s). An attempt of adding more elements would cause UnsupportedOperationException.
Topic: Convert an int array to List<Integer>
int[] priceList = new int[]{7, 1, 5, 3, 6};
List<Integer> priceL = Arrays.stream(priceList).boxed().collect(toList());
https://stackoverflow.com/questions/1073919/how-to-convert-int-into-listinteger-in-java
----------------------------------------
Topic: Given a list of strings, convert them to lowercase, sort them in natural order and return the sorted list
List<String> collect = wordList.stream().map(String::toLowerCase).sorted((Comparator.naturalOrder())).collect(Collectors.toList());
My Code: E:\MyJava\IntellijProjects\collection-self-learn\src\main\java\org\example\puzzle\regex\SentenceAnalyser.java
My GitHub URL: TBD
----------------------------------------
Topic: Given a list of person objects having name and age (or a list of words), get the sum of all the ages
Topic (To do): Given a list of words, get the sum of character count for all the words
Code Snippet:
final int totalAge_2ndMethod = people.stream()
.mapToInt(Person::getAge)
.sum();
System.out.println("totalAge_2ndMethod = " + totalAge_2ndMethod);
See my Trial: E:\MyJava\IntellijProjects\MyJavaMixBagProject\src\main\java\java8practice\PersonDemoJava8.java
GitHub URL: https://github.com/abhishekomp/MyJavaMixBagProject/blob/main/src/main/java/java8practice/PersonDemoJava8.java
----------------------------------------
groupingBy, collectingAndThen, maxBy
Topic: Given a sentence get me the length of the word that has the maximum length
Topic: Given a sentence get me the word that has the maximum length
Topic: Given a list of person objects (name and age) get me the max age
Topic: Given a list of person objects (name and age) get the person having maximum age
Topic: (Hard) Given a list of person objects (name and age) get the person name having maximum age
Topic: (Hard) Given a list of dog objects (name, breed, age) group them by breed and get the max age for each breed.
Topic: Get the person who has the maximum experience
Topic: Get the person who has the least experience
Code Snippet:
For getting the max age from the list of persons
Optional<Person> collect = people.stream()
.collect(maxBy(comparing(Person::getAge)));
//Optional<Person> collect = people.stream().max(comparing(Person::getAge));
----------------------------------------
Topic: Min, Max from a list
Topic: Given a list of integers, get the largest integer from the list
Topic: Given a list of integers, get the index of the largest integer from the list
Topic: Similarly get the smallest integer from the list and its index.
Code Snippet:
int minValIndex = integerList.indexOf(Collections.min(integerList));
int minVal = Collections.min(integerList);
Another way to get the min value from a list of integers
Optional<Integer> minValue = integerList.stream().min(comparing(Function.identity()));
----------------------------------------
Topic: Extract all integers from a String representing the integers
For example, given a string = 1234, get all the integers in a list from this string.
Convert a stream of integers into an array of String representing those integers
Convert a stream of Strings to an array of String
----------------------------------------
2023-11-29
Topic: Reverse a sentence
For example, the string "Dog bites man" should output as "man bites Dog."