0% found this document useful (0 votes)
2 views14 pages

Singleton

The document contains various Java 8 programming examples demonstrating the use of Stream functions to perform operations on lists and arrays, such as finding even numbers, duplicates, sorting, and counting elements. It also includes examples of working with strings to find non-repeated and repeated characters, as well as methods for handling dates and concatenating streams. Each example provides code snippets along with expected outputs.

Uploaded by

rajansj10
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views14 pages

Singleton

The document contains various Java 8 programming examples demonstrating the use of Stream functions to perform operations on lists and arrays, such as finding even numbers, duplicates, sorting, and counting elements. It also includes examples of working with strings to find non-repeated and repeated characters, as well as methods for handling dates and concatenating streams. Each example provides code snippets along with expected outputs.

Uploaded by

rajansj10
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1.

Given a list of integers, find out all the even


numbers that exist in the list using Stream
functions?

import [Link].*;
import [Link].*;

public class EvenNumber{


public static void main(String args[]) {
List<Integer> list = [Link](10,15,8,49,25,98,32);
[Link]()
.filter(n -> n%2 == 0)
.forEach([Link]::println);

/* or can also try below method */

/* When numbers are given as Array int[] arr = {10,15,8,49,25,98,32}; */

Map<Boolean, List<Integer>> list = [Link](arr).boxed()


.collect([Link](num -> num % 2 == 0));
[Link](list);
}
}

Output:
10, 8, 98, 32

2. Given a list of integers, find out all the numbers


starting with 1 using Stream functions?

import [Link].*;
import [Link].*;

public class NumberStartingWithOne{


public static void main(String args[]) {
List<Integer> myList = [Link](10,15,8,49,25,98,32);
[Link]()
.map(s -> s + "") // Convert integer to String
.filter(s -> [Link]("1"))
.forEach([Link]::println);
/* or can also try below method */

/* When numbers are given as Array int[] arr = {10,15,8,49,25,98,32}; */


List<String> list = [Link](arr).boxed()
.map(s -> s + "")
.filter(s -> [Link]("1"))
.collect([Link]());

[Link](list);
}
}

Output:
10, 15

3. How to find duplicate elements in a given integers


list in java using Stream functions?

import [Link].*;
import [Link].*;

/* This will give the output of all repeated number */


public class DuplicateElements {
public static void main(String args[]) {
List<Integer> myList =
[Link](10,15,8,49,25,98,98,32,15);
Set<Integer> set = new HashSet();
[Link]()
.filter(n -> ![Link](n))
.forEach([Link]::println);
}
}

Output:
98, 15 /* Example 98 and 15 are the only repeated values in the list */

/* Way 1 - Gives list of all distinct/unique values */

public static void getDataWithoutDuplicates() {


List<Integer> myList = [Link](1, 1, 85, 6, 2, 3, 65, 6, 45,
45, 5662, 2582, 2, 2, 266, 666, 656);
[Link]().distinct().forEach(noDuplicateData ->
[Link](noDuplicateData));
}
Output : 1 85 6 2 3 65 45 5662 2582 266 666 656

/* Way 2 - Gives list of all distinct/unique values */

public static void getDataWithoutDuplicates() {


List<Integer> myList = [Link](1, 1, 85, 6, 2, 3, 65, 6, 45,
45, 5662, 2582, 2, 2, 266, 666, 656);
Set<Integer> set = new HashSet<>(myList);

// Convert the set back to a list if needed


List<Integer> uniqueData =
[Link]().collect([Link]());

// Print the unique elements


[Link]([Link]::println);
}

Output : 1 65 2 3 6 266 45 656 85 2582 666 5662

/* Way 3 - Gives list of all distinct/unique values */

/* When numbers are given as Array int[] arr =


{10,15,8,49,25,98,98,32,15}; */

List<Integer> list = [Link](arr).boxed().distinct()


.collect([Link]());

4. Given the list of integers, find the first element of


the list using Stream functions?

import [Link].*;
import [Link].*;

public class FindFirstElement{


public static void main(String args[]) {
List<Integer> myList =
[Link](10,15,8,49,25,98,98,32,15);
[Link]()
.findFirst()
.ifPresent([Link]::println);

/* or can also try below single line code */


/* When numbers are given as Array int[] arr =
{10,15,8,49,25,98,98,32,15}; */
[Link](arr).boxed().findFirst().ifPresent([Link]::print);
}
}

Output:
10

5. Given a list of integers, find the total number of


elements present in the list using Stream functions?

import [Link].*;
import [Link].*;

public class FindTheTotalNumberOfElements{


public static void main(String args[]) {
List<Integer> myList =
[Link](10,15,8,49,25,98,98,32,15);
long count = [Link]()
.count();
[Link](count);

/* or can also try below line code */


/* When numbers are given as Array int[] arr =
{10,15,8,49,25,98,98,32,15}; */
[Link](arr).boxed().count();
}
}

Output:
9

6. Given a list of integers, find the maximum value


element present in it using Stream functions?

import [Link].*;
import [Link].*;

public class FindMaxElement{


public static void main(String args[]) {
List<Integer> myList =
[Link](10,15,8,49,25,98,98,32,15);
int max = [Link]()
.max(Integer::compare)
.get();
[Link](max);

/* or we can try using below way */


/* When numbers are given as Array int[] arr =
{10,15,8,49,25,98,98,32,15}; */

int maxdata = [Link](arr).boxed()


.max([Link]()).get();

[Link](maxdata);
}
}

Output:
98

7. Given a String, find the first non-repeated


character in it using Stream functions?

import [Link].*;
import [Link].*;
import [Link];

public class FirstNonRepeated{


public static void main(String args[]) {
String input = "Java articles are Awesome";

Character result = [Link]() // Stream of String


.mapToObj(s -> [Link]([Link]((char)
s))) // First convert to Character object and then to lowercase
.collect([Link]([Link](),
LinkedHashMap::new, [Link]())) //Store the chars in map with
count
.entrySet()
.stream()
.filter(entry -> [Link]() == 1L)
.map(entry -> [Link]())
.findFirst()
.get();
[Link](result);

/* or can also try using */

[Link]().mapToObj(c -> (char) c)


.filter(ch -> [Link](ch) == [Link](ch))
.findFirst().orElse(null);
}
}

Output:
j

8. Given a String, find the first repeated character in


it using Stream functions?

import [Link].*;
import [Link].*;
import [Link];

public class FirstRepeated{


public static void main(String args[]) {
String input = "Java Articles are Awesome";

Character result = [Link]() // Stream of String


.mapToObj(s ->
[Link]([Link]((char) s))) // First convert to
Character object and then to lowercase
.collect([Link](Function.
identity(), LinkedHashMap::new, [Link]())) //Store the chars
in map with count
.entrySet()
.stream()
.filter(entry -> [Link]() > 1L)
.map(entry -> [Link]())
.findFirst()
.get();
[Link](result);

/* or can also try */

Set<Character> seenCharacters = new HashSet<>();

return [Link]()
.mapToObj(c -> (char) c)
.filter(c -> ![Link](c))
.findFirst()
.orElse(null);
}
}

Output:
a
9. Given a list of integers, sort all the values present
in it using Stream functions?

import [Link].*;
import [Link].*;
import [Link];

public class SortValues{


public static void main(String args[]) {
List<Integer> myList =
[Link](10,15,8,49,25,98,98,32,15);

[Link]()
.sorted()
.forEach([Link]::println);

/* Or can also try below way */


/* When numbers are given as Array int[] arr =
{10,15,8,49,25,98,98,32,15}; */

[Link](arr).boxed().sorted().collect([Link]())
}
}

Output:
8
10
15
15
25
32
49
98
98

10. Given a list of integers, sort all the values present


in it in descending order using Stream functions?

import [Link].*;
import [Link].*;
import [Link];

public class SortDescending{


public static void main(String args[]) {
List<Integer> myList =
[Link](10,15,8,49,25,98,98,32,15);
[Link]()
.sorted([Link]())
.forEach([Link]::println);
}
}

Output:
98
98
49
32
25
15
15
10
8

11. Given an integer array nums, return true if any value


appears at least twice in the array, and return false if
every element is distinct.

public boolean containsDuplicate(int[] nums) {


List<Integer> list = [Link](nums)
.boxed()
.collect([Link]());
Set<Integer> set = new HashSet<>(list);
if([Link]() == [Link]()) {
return false;
}
return true;

/* or can also try below way */


Set<Integer> setData = new HashSet<>();
return [Link](nums)
.anyMatch(num -> ![Link](num));
}

Input: nums = [1,2,3,1]


Output: true

Input: nums = [1,2,3,4]


Output: false
12. How will you get the current date and time using
Java 8 Date and Time API?

class Java8 {
public static void main(String[] args) {
[Link]("Current Local Date: " +
[Link]());
//Used LocalDate API to get the date
[Link]("Current Local Time: " +
[Link]());
//Used LocalTime API to get the time
[Link]("Current Local Date and Time: " +
[Link]());
//Used LocalDateTime API to get both date and time
}
}

13. Write a Java 8 program to concatenate two


Streams?

import [Link];
import [Link];
import [Link];

public class Java8 {


public static void main(String[] args) {

List<String> list1 = [Link]("Java", "8");


List<String> list2 = [Link]("explained", "through",
"programs");

Stream<String> concatStream = [Link]([Link](),


[Link]());

// Concatenated the list1 and list2 by converting them into Stream

[Link](str -> [Link](str + " "));

// Printed the Concatenated Stream

}
}
14. Java 8 program to perform cube on list elements
and filter numbers greater than 50.

import [Link].*;

public class Main {


public static void main(String[] args) {
List<Integer> integerList = [Link](4,5,6,7,1,2,3);
[Link]()
.map(i -> i*i*i)
.filter(i -> i>50)
.forEach([Link]::println);
}
}

Output:
64
125
216
343

15. Write a Java 8 program to sort an array and then


convert the sorted array into Stream?

import [Link];

public class Java8 {

public static void main(String[] args) {


int arr[] = { 99, 55, 203, 99, 4, 91 };
[Link](arr);
// Sorted the Array using parallelSort()

[Link](arr).forEach(n > [Link](n + " "));


/* Converted it into Stream and then
printed using forEach */
}
}

16. How to use map to convert object into Uppercase


in Java 8?
public class Java8 {

public static void main(String[] args) {


List<String> nameLst = [Link]()
.map(String::toUpperCase)
.collect([Link]());
[Link](nameLst);
}
}

output:
AA, BB, CC, DD

17. How to convert a List of objects into a Map by


considering duplicated keys and store them in sorted
order?

public class TestNotes {

public static void main(String[] args) {

List<Notes> noteLst = new ArrayList<>();


[Link](new Notes(1, "note1", 11));
[Link](new Notes(2, "note2", 22));
[Link](new Notes(3, "note3", 33));
[Link](new Notes(4, "note4", 44));
[Link](new Notes(5, "note5", 55));

[Link](new Notes(6, "note4", 66));

Map<String, Long> notesRecords = [Link]()


.sorted(Comparator
.comparingLong(Notes::getTagId
)
.reversed()) // sorting is
based on TagId 55,44,33,22,11
.collect([Link]
(Notes::getTagName,
Notes::getTagId,
(oldValue, newValue) ->
oldValue,LinkedHashMap::new));
// consider old value 44 for dupilcate key
// it keeps order
[Link]("Notes : " + notesRecords);
}
}
18. How to count each element/word from the String
ArrayList in Java8?

public class TestNotes {

public static void main(String[] args) {


List<String> names = [Link]("AA", "BB", "AA", "CC");
Map<String,Long> namesCount = names
.stream()
.collect(
[Link](
[Link](),
[Link]()));
[Link](namesCount);
}
}

Output:
{CC=1, BB=1, AA=2}

19. How to find only duplicate elements with its count


from the String ArrayList in Java8?

public class TestNotes {

public static void main(String[] args)


List<String> names = [Link]("AA", "BB", "AA", "CC");
Map<String,Long> namesCount = names
.stream()
.filter(x->[Link](names, x)>1)
.collect([Link]
([Link](), [Link]()));
[Link](namesCount);

/*or you can also try using */

Map<String, Long> namesCount = [Link]()


.collect([Link]([Link](),
[Link]()))
.entrySet()
.stream()
.filter(entry -> [Link]() > 1)
.collect([Link]([Link]::getKey,
[Link]::getValue));
}
}
Output:
{AA=2}

20. How to check if list is empty in Java 8 using


Optional, if not null iterate through the list and print
the object?

[Link](noteLst)
.orElseGet(Collections::emptyList) // creates empty immutable
list: [] in case noteLst is null
.stream().filter(Objects::nonNull) //loop throgh each object
and consider non null objects
.map(note -> Notes::getTagName) // method reference, consider
only tag name
.forEach([Link]::println); // it will print tag names

21. Write a Program to find the Maximum element in an


array?

public static int findMaxElement(int[] arr) {


return [Link](arr).max().getAsInt();
}

Input: 12,19,20,88,00,9
output: 88

22. Write a program to print the count of each character in


a String?

public static void findCountOfChars(String s) {


Map<String, Long> map = [Link]([Link](""))
.map(String::toLowerCase)
.collect(Collectors
.groupingBy(str -> str,
LinkedHashMap::new,
[Link]()));

// or you can also try using [Link]() instead of LinkedHashMap

Map<String, Long> mapObject = [Link]([Link](""))


.map(String::toLowerCase)
.collect([Link]([Link](),
[Link]()));

Input: String s = "string data to count each character";


Output: {s=1, t=5, r=3, i=1, n=2, g=1, =5, d=1, a=5, o=2, c=4, u=1, e=2,
h=2

You might also like