50 different types of Java Stream API Examples

1. Count the Characters from a String

String str = "Chennai";
Map<Character, Long> result = str.chars()
   .mapToObj((a)->(char)a)
   .collect(Collectors.groupingBy(
     Function.identity(),Collectors.counting()));
System.out.println(result);

2. Convert character into lower case

String str2 = "Chennai is My City";
String stream = str2.chars()
.mapToObj(val->String.valueOf((char)val))
.filter(a->!a.isBlank())
.map(a->a.toLowerCase())
.collect(Collectors.joining());
System.out.println(stream);

3. Count the unique letters

String str21 = "Chennai is My City";
Long slength = str2.chars()
.mapToObj(val->String.valueOf((char)val))
.distinct()
.filter(a->!a.isBlank())
.collect(Collectors.counting());
int totalChar = Arrays.stream(str21.split(""))
.distinct()
.filter(a->!a.isBlank())
.collect(Collectors.counting()).intValue();
System.out.println(slength+" "+totalChar);
String str3 = "Madurai is my City";
String op3 = IntStream.range(0, str3.length())
		.map(val-> val%2==0 ? str3.toUpperCase().charAt(val) : str3.charAt(val))
		.mapToObj(val->String.valueOf((char)val))
		.collect(Collectors.joining());
System.out.println(op3);
System.out.println("--------------------");

4. Extract all words starting with a specific letter from a sentence

String str01 = "Hello My Day Went Well";
		String op01 = Arrays.stream(str01.split(" ")).filter(val->val.startsWith("W")).collect(Collectors.joining(" "));
		System.out.println(op01);
		System.out.println("--------------------");

5. Check if a string contains any digits

String str02 = "Hello My Day0%";
String op02 = Arrays.stream(str02.split(""))
.filter(val->!Character.isDigit(val.charAt(0)))
.collect(Collectors.joining());
System.out.println(op02);
System.out.println("--------------------");

6. Check if a string contains any special character except space

String str03 = "Hello My Day0%";
String op03 = Arrays.stream(str03.split(""))
.filter(val->Character.isSpaceChar(val.charAt(0)) || Character.isLetter(val.charAt(0)) )
.collect(Collectors.joining());
System.out.println(op03);
System.out.println("--------------------");

7. Find the index of the first repeated character in a string

String str04 = "Hello My Day";
Set<Character> set= new HashSet<>();
int res04 = IntStream.range(0, str04.length())
.filter(val->!set.add(str04.charAt(val)))
.findFirst()
.getAsInt();
System.out.println(res04);
System.out.println("--------------------");

8. Find the second longest word in a sentence

String str05 = "I am Here for the second largest word";
String aString =Arrays.stream(str05.split(" "))
.sorted(Comparator.comparingInt(String::length)
.reversed())
.skip(1)
.findFirst()
.orElse(null);
System.out.println(aString);
System.out.println("--------------------");

9. Find the second most frequent character in a string

String str06 = "I am Here for the the second and the most used second word";
Map<String,Long> cnt =Arrays.stream(str06.split(" ")).collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));

Map<String,Long> cnt1 = cnt.entrySet().stream()			.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.skip(3)
.limit(1)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(a,b)->a,LinkedHashMap::new));

System.out.println(cnt1);
System.out.println("--------------------");

10. Extract all substrings of a given length from a string

String str07 = "I am Here extract the second and the most used second word";
int length = 2;
Arrays.stream(str07.split(" "))
.filter(val->val.length()==length)
.forEach(System.out::println);

List<String> list = Arrays.stream(str07.split(" "))
.filter(val->val.length()==length)
.collect(Collectors.toList());

list.forEach(System.out::println);
System.out.println("--------------------");

11. Remove all duplicate characters except the first occurrence from a word

String str08 = "I am Here remove the second and the most used second word";
Arrays.stream(str08.split(" "))
.map(val-> Arrays.stream(val.split(""))
                 .distinct()
                 .collect(Collectors.joining()))
.forEach(System.out::println);

Arrays.stream(str08.split(" "))
      .map(val-> val.chars()
              .distinct()
              .mapToObj(a->String.valueOf((char)a))
              .collect(Collectors.joining()))
.forEach(System.out::println);
System.out.println("--------------------");

12. Remove all duplicate characters except the first occurrence from a string

String str09 = "Here";
String res01 = str09.chars()
                    .distinct()
                    .mapToObj(b->String.valueOf((char)b))
                    .collect(Collectors.joining());
System.out.println(res01);
System.out.println("--------------------");

13.Remove all the words containing duplicate characters

String str10 = "Hello Have a Cool Day";
String res010 =  Arrays.stream(str10.split(" "))
		.map(val-> val.equals(val.chars()
                               .distinct()
   		               .mapToObj(a>String.valueOf((char)a))
                               .collect(Collectors.joining())) ? val : "")
                .collect(Collectors.joining(" "));
System.out.println(res010);		
System.out.println("--------------------");

14. Replace every second word in a sentence with a specific word

String str11 = "Hello Have a Cool Day";
List<String> list2 = Arrays.asList(str11.split(" "));
IntStream.range(0, list2.size())
.forEach(a-> {
        if ((a-1)%2==0) {
	         list2.set(a, "Siva");
	        }
});
System.out.println(list2);
System.out.println("--------------------");

15. Find all unique characters in a string

String string11 = "I am the Data";
Map<String, Long> mapSMap =  Arrays.stream(string11.split(""))
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()));
Set<String> saSet= mapSMap.keySet();
System.out.println(saSet);
System.out.println(mapSMap.entrySet().stream()
.filter(a->a.getValue()==1)
.collect(Collectors.toList()));

16. Grouping basis on Special Charactors Examples

String string12 = "I am the Complicated Data and a normal data and i am the! only one";
Map<Object, Long> map = Arrays.stream(string12.split(" "))
.map(a->a.replaceAll("[^a-zA-Z0-9 ]", ""))
.collect(Collectors.groupingBy(a->a.equalsIgnoreCase(a),Collectors.counting()));
System.out.println(map);
		
String strGrpString = "I am the Example for Multilevel GroupingBy and You know who i am";
Map<Object,Map<Object, List<String>> > oMap =  Arrays.stream(strGrpString.split(" "))
.collect(Collectors.groupingBy(a->a.length(),Collectors.groupingBy(a->a.startsWith("a"))));
		
oMap.entrySet().forEach(a->System.out.println(a.getKey()+"  :  "+a.getValue())   );

17. Ordering the Map by Key and Collect as a Map

Map<String, Integer> orderedMap =  mapData.entrySet()  											.stream()											.sorted(Map.Entry.comparingByValue())											.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(a,b)->b,LinkedHashMap::new));
System.out.println("Ordering the Map by Key and Collect as a Map : "+orderedMap);

18. Ordering the Map by Value Reverse Order and Collect as a Map

 Map<String, Integer> orderedMapValue = mapData.entrySet()	  									.stream()					.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))		  									.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(a,b)->a,LinkedHashMap::new));
System.out.println("Ordering the Map by Value Reverse Order and Collect as a Map : "+orderedMapValue);	

19. Ordering the Map by Key Order and Collect as a Map

Map<String, Integer> orderedMapKey = mapData.entrySet()	  									.stream()	  									.sorted(Map.Entry.comparingByKey())  									.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(a,b)->a,LinkedHashMap::new));
System.out.println("Ordering the Map by Key Order and Collect as a Map : "+orderedMapKey);

20. Ordering the Map by Key ReverseOrder and Collect as a Map

Map<String, Integer> orderedMapKeyReverse = mapData.entrySet()		  									.stream()	  									.sorted(Map.Entry.comparingByKey(Comparator.reverseOrder()))	  									.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,(a,b)->a,LinkedHashMap::new));
System.out.println("Ordering the Map by Key ReverseOrder and Collect as a Map : "+orderedMapKeyReverse);

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *