Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added new stream question for Extracting unique matching strings from string array #1

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -130,3 +130,9 @@ This repository contains sample Java 8 coding questions that can be used for int
32. **Calculate the age of a person in years**

Write a Java 8 program to calculate the age of a person in years given their birthday.

33. **Extract unique matching strings from String array**

Write a Java 8 program to extract Unique String starting with "#" from the String array Using Java Streams.


25 changes: 24 additions & 1 deletion src/com/rohit/Sample.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import java.time.Period;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

Expand Down Expand Up @@ -249,6 +250,13 @@ public static void main(String[] args) {
* Write a Java 8 program to calculate the age of a person in years given their birthday.
*/
calculatePersonAgeInYear();

/**
* Extract unique matching strings from String array
*
* Write a Java 8 program to extract Unique String starting with "#" from the String array Using Java Streams
*/
extractUniqueStringStartingWithHashtag();
}

private static void calculatePersonAgeInYear() {
Expand Down Expand Up @@ -607,4 +615,19 @@ private static void separationOfEvenOddNumberInMap() {

System.out.println(evenAddOddSeparation);
}
}

private static void extractUniqueStringStartingWithHashtag() {
String[] input = new String[]{
"This JEP is #mainly for scientific #applications",
"and it makes #floating-point operations consistently #strict.",
"The default #floating-point operations are #strict or strictfp,"
};

List<String> output = Arrays.stream(input).flatMap(line -> Arrays.stream(line.split(" ")))
.filter(word -> word.startsWith("#"))
.map(str -> "#" + str.substring(1).replaceAll("^\\W+|\\W+$", ""))
.distinct()
.collect(Collectors.toList());
output.forEach(System.out::println);
}
}