Skip to content

Instantly share code, notes, and snippets.

@prembhaskal
Last active June 30, 2023 13:42
Show Gist options
  • Save prembhaskal/556f0a9637b4e6ac5481970085a86b62 to your computer and use it in GitHub Desktop.
Save prembhaskal/556f0a9637b4e6ac5481970085a86b62 to your computer and use it in GitHub Desktop.
Java Stream questions.
package basics;
import java.util.Arrays;
public class CountStream {
public static void main(String[] args) {
System.out.printf("hello world\n");
int[] nums = new int[]{0, 1, 2, 3, 4, 2, 1, 4, 5, 1};
long cnt = Arrays.stream(nums).boxed()
.count();
printf("counts: %d\n", cnt);
}
public static void printf(String msg, Object... s) {
System.out.printf(msg, s);
}
}
package basics;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Distinct {
public static void main(String[] args) {
System.out.printf("hello world\n");
int[] nums = new int[]{0, 1, 2, 3, 4, 2, 1, 4, 5, 1};
Set<Integer> set = new HashSet<>();
Arrays.stream(nums).boxed().filter((num) -> {
return set.add(num);
}).forEach(num -> printf("%d ", num));
}
public static void printf(String msg, Object... s) {
System.out.printf(msg, s);
}
}
package basics;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.Map;
public class FindFirst {
public static void main(String[] args) {
System.out.printf("hello world\n");
int[] nums = new int[]{0, 1, 2, 3, 4, 2, 1, 4, 5, 1};
Arrays.stream(nums).boxed()
.findFirst()
.ifPresent(num -> printf("%d", num));
}
public static void printf(String msg, Object... s) {
System.out.printf(msg, s);
}
}
package basics;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
public class FirstNonRepeat {
public static void main(String[] args) {
try {
System.out.printf("hello world\n");
int[] nums = new int[]{5, 0, 1, 2, 3, 4, 2, 1, 4, 6, 1};
BiConsumer<Map<Integer, Integer>, Integer> countingmap = (map, num) -> map.put(num, map.getOrDefault(num, 0) + 1);
Arrays.stream(nums).boxed()
.collect(LinkedHashMap::new, countingmap, Map::putAll) // get all frequencies
// collect is intermediate stateful, so this does not really help in stream sense.
// basically this question cannot be solved until we see the whole stream :(
.entrySet().stream()
.filter((entry) -> entry.getValue() == 1) // find non duplicates
.findFirst() // find first among them
.ifPresent(val -> printf("first non repeating is : %s\n", val.getKey()));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void printf(String msg, Object... s) {
System.out.printf(msg, s);
}
}
package basics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
public class GroupingBy {
public static void main(String[] args) {
try {
System.out.printf("hello world\n");
var books = new ArrayList<Book>();
books.add(new Book("harry potter", "YA"));
books.add(new Book("thinking fast and slow", "pyschology"));
books.add(new Book("terminator", "science_fiction"));
books.add(new Book("computer graphics", "education"));
books.add(new Book("definitive cassandra", "education"));
books.stream()
.collect(Collectors.groupingBy(Book::getGenre)) // method reference, equivalent to (Book b) -> {return b.getGenre}
.forEach((genre, genbooks) -> {
printf("for genre: %s, books: %s\n", genre, genbooks);
});
} catch (Exception e) {
e.printStackTrace();
}
}
public static void printf(String msg, Object... s) {
System.out.printf(msg, s);
}
}
class Book {
String genre;
String name;
Book(String nm, String gen) {
this.name = nm;
this.genre = gen;
}
public String getGenre() {
return genre;
}
public String getName() {
return name;
}
@Override
public String toString() {
return String.format("name: %s", name);
}
}
package basics;
import java.util.Arrays;
import java.util.function.BinaryOperator;
public class IntegerSum {
public static void main(String[] args) {
System.out.printf("hello world\n");
int[] nums = new int[]{0, 1, 2, 3, 4, 2, 1, 4, 5, 1};
BinaryOperator<Integer> sumop = (Integer a, Integer b) -> a + b; // can use Integer::sum here
Arrays.stream(nums).boxed()
.reduce(sumop)
.ifPresent(sum -> printf("%d", sum));
}
public static void printf(String msg, Object... s) {
System.out.printf(msg, s);
}
}
package basics;
import java.util.Arrays;
public class MaxInteger {
public static void main(String[] args) {
System.out.printf("hello world\n");
int[] nums = new int[]{0, 1, 2, 3, 4, 2, 1, 4, 5, 1};
// using reduce
int max = Arrays.stream(nums).boxed()
.reduce(-1, Math::max);
printf("max element: %d\n", max);
// another using max method from Stream
Arrays.stream(nums).boxed()
.max(Integer::compareTo)
.ifPresent(num -> printf("max method: %d\n", num));
}
public static void printf(String msg, Object... s) {
System.out.printf(msg, s);
}
}
package basics;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.Map;
public class PrintDuplicate {
public static void main(String[] args) {
System.out.printf("hello world\n");
int[] nums = new int[]{0, 1, 2, 3, 4, 2, 1, 4, 5, 1};
Map<Integer, Integer> freq = new HashMap<>();
Arrays.stream(nums).boxed()
.filter(num -> {
var cnt = freq.getOrDefault(num, 0);
if (cnt > 0) {
return true;
}
freq.put(num, cnt + 1);
return false;
})
.distinct()
.forEach(num -> printf("%d ", num));
printf("\n");
// using set
Set<Integer> set = new HashSet<>();
Arrays.stream(nums).boxed()
.filter( num -> !set.add(num))
.distinct()
.forEach(num -> printf("%d ", num));
}
public static void printf(String msg, Object... s) {
System.out.printf(msg, s);
}
}
package basics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class PrintEvenStream {
public static void main(String[] s) {
System.out.printf("hello world\n");
int[] nums = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
var evenlist1 = Arrays.stream(nums)
.filter((num) -> num % 2 == 0)
.collect(ArrayList::new, List::add, List::addAll);
printf("even nos list is here: %s\n", evenlist1);
// with boxed
var evenlist2 = Arrays.stream(nums)
.boxed()
.filter((num) -> num % 2 == 0)
.toList();
printf("boxed even nos. list : %s\n", evenlist2);
// print directly
Arrays.stream(nums)
.filter((num) -> num % 2 == 0)
.forEach((num) -> printf("%d ", num));
}
public static void printf(String msg, Object... s) {
System.out.printf(msg, s);
}
}
package basics;
import java.util.Arrays;
import java.util.function.Predicate;
public class PrintNumStartWithOne {
public static void main(String[] args) {
System.out.printf("hello world\n");
int[] nums = new int[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 3034, 120304, 3404 , 01, 34,};
Predicate<Integer> filter = (num) -> {
int digit = -1;
for (;num > 0;){
digit = num % 10;
num = num / 10;
}
return digit == 1;
};
Arrays.stream(nums).boxed()
.filter(filter)
.forEach((num) -> printf("%d ", num));
printf("\n");
// With string functions
Arrays.stream(nums).boxed()
.map(String::valueOf)
.filter((s) -> s.startsWith("1"))
.forEach(s -> printf("%s ", s));
}
public static void printf(String msg, Object... s) {
System.out.printf(msg, s);
}
}
package basics;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class StreamGenerator {
public static void main(String[] args) {
try {
System.out.printf("hello world\n");
// finite stream
IntStream.range(0, 100)
.boxed()
.filter((num) -> num % 3 == 0 || num % 7 == 0)
.forEach(num -> printf("%d ", num));
// infinite stream
printf("\n\n");
IntStream.iterate(0, e -> e + 3)
.boxed()
.limit(150)
.filter((num) -> num % 13 == 0)
.forEach(num -> printf("%d ", num));
} catch (Exception e) {
e.printStackTrace();
}
}
public static void printf(String msg, Object... s) {
System.out.printf(msg, s);
}
}
package basics;
import java.util.Arrays;
import java.util.function.BinaryOperator;
public class StreamSum {
public static void main(String[] args) {
System.out.printf("hello world\n");
int[] nums = new int[]{0, 1, 2, 3, 4, 2, 1, 4, 5, 1};
BinaryOperator<Integer> sumop = (Integer a, Integer b) -> a + b; // can use Integer::sum here
Arrays.stream(nums).boxed()
.reduce(sumop)
.ifPresent(sum -> printf("%d", sum));
}
public static void printf(String msg, Object... s) {
System.out.printf(msg, s);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment