Java Substring Comparisons

  • + 0 comments

    Solution using JAVA 8

    public static String getSmallestAndLargest(String s, int k){
            List<String> subStrings = 
            IntStream.rangeClosed(0, s.length()-k)
                    .mapToObj(i -> s.substring(i,i+k))
                    .sorted(Comparator.naturalOrder())
                    .collect(Collectors.toList());
                
            String smallest = subStrings.get(0);
            String largest = subStrings.get(subStrings.size()-1);
                    
            return smallest+"\n"+largest;
        }