In this post, we need to have a look one of the important coding interview questions asked for java 8 streams. Given list contains either String or Integers. Refer all coding questions here
1) Print duplicate elements using frequency and toSet methods .
In the below code used Collections.frequency to filter the data with occurance value greater than 1 and toSet method used to remove the duplicated in output.
import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.stream.Collectors; public class Java8StreamEx { public static void main(String[] args) { List<Integer> integerList = Arrays.asList(2, 3, 3, 5, 6, 6, 6); Set<Integer> list = integerList.stream().filter( s -> Collections.frequency(integerList, s) > 1)
.collect(Collectors.toSet()); list.stream().forEach(s -> System.out.println("Duplicate element - "+s)); } }
Output:- Duplicate element - 3
Duplicate element - 6
2) Using frequency and toMap method(map used to store element with occurance)
Used frequency and toMap method to store duplicates into the Map with occurance as a value.
import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public class Java8StreamEx { public static void main(String[] args) { List<Integer> integerList = Arrays.asList(2, 3, 3, 5, 6, 6, 6); // store duplicate into the map Map<Integer, Long> map =
integerList.stream().filter( s -> Collections.frequency(integerList, s) > 1).collect( Collectors.toMap(Function.identity(), v -> 1L, Long::sum)); map.entrySet().stream().forEach(s -> System.out.println(s)); } }
Output: - 3=2
6=3
3) Using groupingBy and counting methods - group the similar elements and to find the occarance used counting.
To write the code to find the duplicate using groupingBy,
import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; public class Java8StreamEx { public static void main(String[] args) { List<String> listOfString = Arrays.asList("A", "B", "C", "A", "A", "D", "B"); Map<String, Long> mapOfStrings = listOfString.stream().filter( s -> Collections.frequency(listOfString, s) > 1) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); mapOfStrings.entrySet().stream().forEach(s -> System.out.println(s)); } }
Output:-A=3
B=2
Thank you for visiting blog.
Refer the post for coding questions - coding questions
No comments:
Post a Comment