Programs - Yash-777/MyWorld GitHub Wiki

Find the Number of Occurrences of a Substring in a String stackpost: Fromula: (source.split(Pattern.quote("aa"), -1).length - 1) or (str.length() - str.replaceAll(Pattern.quote(subStr), "").length()) / subStr.length()

Instead of using direct subString in str.replaceAll(subStr, "") we are using Pattern.quote(subStr) in replaceAll str.replaceAll(java.util.regex.Pattern.quote(subStr), "") to support SpecialChars like (+).

public static void main(String[] args) {
    System.out.println( countOfOccurrences(source, charSeq) ); // 2
    System.out.println( countOfOccurrences(source, "Yash") );  // 1
    System.out.println( countOfOccurrences(source, "aa") );    // 6
    
    System.out.println( source.split(Pattern.quote(charSeq), -1).length-1 ); // 2
    System.out.println( source.split(Pattern.quote("aa"), -1).length - 1 );  // 6
}
public static int countOfOccurrences(String str, String subStr) {
    int strLength = str.length();
    int replaceLength = str.replaceAll(java.util.regex.Pattern.quote(subStr), "").length();
    int subStringLength = subStr.length();
    
    System.out.format("strLength:%d, replaceLength:%d, subStringLength:%d\n", strLength, replaceLength, subStringLength);
    return (strLength - replaceLength) / subStringLength;
}

String Reverse Java8 stackpost
String str = "Hello World";
int strLength = str.length();
IntFunction<String> reverseMapper = (i) -> Character.toString( ( str.charAt( strLength -1 - i) ) );

String reverseString = IntStream.range(0, strLength) // for (int i = 0; i < strLength ; i++) { ... }
		.mapToObj( reverseMapper )                 // array[ lastElement ]
		.collect(Collectors.joining())             // Joining stream of elements together into a String.
		.toString();                               // This object (which is already a string!) is itself returned.

System.out.println("Reverse Stream as String : "+ reverseString);
public static String reverseString_Stream(String str) {
    IntStream cahrStream = str.chars();
    int[] array = cahrStream.map( x -> x ).toArray();

    IntFunction<String> reverseMapper = (i) -> ( Character.toString((char) array[ array.length -1 - i ]) );
                                      //(i) -> ( Character.toString((char) array[ (array.length - i) + (0 - 1) ]) );

    String reverseString = IntStream.range(o, array.length) // for (int i = from; i < upTo ; i++) { ... }
            .mapToObj( reverseMapper )                 // array[ lastElement ]
            .collect(Collectors.joining())             // Joining stream of elements together into a String.
            .toString();                               // This object (which is already a string!) is itself returned.

    System.out.println("Reverse Stream as String : "+ reverseString);
    return reverseString;
}
String str = "Hello World";
    
// Reverse the string using StringBuilder and Stream
String reversed = str.chars()
    .mapToObj(c -> String.valueOf((char) c))
    .collect(Collectors.collectingAndThen(Collectors.toList(),
        lst -> {
          StringBuilder sb = new StringBuilder();
          for (int i = lst.size() - 1; i >= 0; i--) {
            sb.append(lst.get(i));
          }
          return sb;
        })).toString();

System.out.println("Original: " + str);
System.out.println("Reversed: " + reversed);

Array Reverse Java8
int[] arr = {333,444,5551, 4454, 11222};
IntFunction<Integer> reverseMapperArray = (i) -> ( arr[ arr.length -1 - i] );
Integer[] reverseArr = IntStream.range(0, arr.length)
		.mapToObj(reverseMapperArray)
		.toArray(Integer[]::new);
//System.out.println(  Arrays.asList(reverseArr) );
System.out.println( Arrays.toString(reverseArr) );
//Arrays.stream(reverseArr).forEach(System.out::println);
//Stream.of(reverseArr).forEach(System.out::println);

Common, Left, Right elements of two arrays {1, 5, 7, 3, 4, 5, 5} {5, 6, 7, 2, 8, 0} : Left:[1, 3, 4], Right:[6, 2, 8, 0], Common:[5, 7]
// Join - Left, Common, Right
Integer[] arr1 = {1, 5, 7, 3, 4, 5, 5};
int[] arr2 = {5, 6, 7, 2, 8, 0};

List<Integer> arr1List = Arrays.asList(arr1); // AutoBoxing is not allowed here.
List<Integer> arr2List = Arrays.stream( arr2 )
		.mapToObj( i -> i )  // int to Integer (AutoBoxing)
		.collect(Collectors.toList());

List<Integer> leftJoin = arr1List.stream().filter(i -> !arr2List.contains(i)).collect(Collectors.toList());
List<Integer> rightJoin = arr2List.stream().filter(i -> !arr1List.contains(i)).collect(Collectors.toList());
List<Integer> common = arr1List.stream().filter(i -> arr2List.contains(i)).distinct().collect(Collectors.toList());
System.out.println("Left:"+leftJoin);   // [1, 3, 4]
System.out.println("Right:"+rightJoin); // [6, 2, 8, 0]
System.out.println("Common:"+common);   // [5, 7]

Program which takes Input array [32, 323, 333, 444, 5551, 4454, 11222, 1] and generates output array having common digits [333, 444, 1]
public static void arrayIndexValueUniqueDigit() {
    int[] arr = {32, 323, 333, 444, 5551, 4454, 11222, 1, 121, 11, 12};
    
    int[] output = new int[arr.length];
    int oi = 0;
    for(int i = 0; i < arr.length; i++) {
        String arrStr = String.valueOf(arr[i]);
        
        char[] charArray = arrStr.toCharArray();
        
//        Arrays.sort(charArray);
//        System.out.println(charArray[0] +":---- :"+ charArray[charArray.length -1] );
//        if(charArray[0] == charArray[c.length -1]) output[oi++] = Integer.valueOf( arrStr );
        
        String firstDigit = ""+ charArray[0];
        for(int j = 0; j < charArray.length; j++) {
            if(j == 0) firstDigit = charArray[j]+"";
            else if (j > 0 && !(firstDigit.equals( charArray[j]+"" ))) break;
            
            if (j+1 == charArray.length && firstDigit.equals( charArray[j]+"" ) ) // last value check
            output[oi++] = Integer.valueOf( arrStr );
        }
        
    }
    System.out.println( Arrays.toString(output) );//[333, 444, 1, 11, 0, 0, 0, 0, 0, 0, 0]
}

public static void main(String[] args) {
    int[] inputArray = {32, 323, 333, 444, 5551, 4454, 11222, 1, 121, 11, 12};
    
    int[] outputArray = Arrays.stream(inputArray)
        .filter(i -> hasSameDigits(i))
        .toArray();
        
    System.out.println(Arrays.toString(outputArray)); // [333, 444, 1, 11]
}
public static boolean hasSameDigits(int n) {
    String digits = Integer.toString(n);
    char[] charArray = digits.toCharArray();
    char firstDigit = charArray[0];

    for (char c : charArray) {
      if (c != firstDigit) {
        return false;
      }
    }
    return true;
}

Explanation:

  • The Arrays.stream() method is used to convert the input array to a stream of integers.
  • The filter() method is used to filter out any elements that do not have the same digits. This is achieved using the hasSameDigits() method, which checks if all the digits in the number are the same.
  • Finally, the toArray() method is used to convert the filtered stream back into an integer array.
  • The output array is then printed to the console using the Arrays.toString() method.
  • The hasSameDigits() method works by converting the integer to a string, and then checking if all the characters in the string are the same. If they are, the method returns true, otherwise it returns false.


Map Sort based on Keys and Values
SortedMap<String, Object> map = new TreeMap<>();
Map<Integer, String> map = new HashMap<>(); // TreeMap - Direct sort based on key
map.put(10, "y");
map.put(5, "c");
map.put(50, "a");
map.put(4, "s");
map.put(7, "z");
map.put(1, "y");
System.out.println("Input Map: "+map);

Sort on List of Entries:

// Create a linked list from the above map entries
List<Map.Entry<Integer, String>> list = new LinkedList<>(map.entrySet());
list.sort( Comparator.comparing(Map.Entry::getValue) );
System.out.println("List<Map.Entry<Integer, String>> Value Sort:"+list);
list.sort( Comparator.comparing(Map.Entry::getKey)   );
System.out.println("List<Map.Entry<Integer, String>> Key   Sort:"+list);

Map sort based on key's and Value's

Map<Integer, String> result = map.entrySet().stream()
    //.sorted(Map.Entry.comparingByKey()) //.sorted(Map.Entry.comparingByValue())
    .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))  // HashMap
    //.sorted(Map.Entry.<String, Integer>comparingByValue().reversed()) //LinkedHashMap
    
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); // sorted stream map
    //.collect(Collectors.toMap(k -> k.getKey(), e -> (String) e.getValue())); // Normal Map
System.out.println("Map Entries: "+ result); // {7=z, 1=y, 10=y, 4=s, 5=c, 50=a}


ArrayList<Integer> al = new ArrayList<Integer>(); // Generics - Type argument
al.add(10);
al.add(30);
al.add(1, 20); // add(index, object)


HashMap<Integer, String> map = new HashMap<Integer, String>(); // nulls are accepted for k,v
map.put(null, null);
map.put(10, null);
map.put(10, "hai");
map.putIfAbsent(10, "modi");
System.out.println(map);

ConcurrentHashMap<Integer, String> cmap = new ConcurrentHashMap();
//cmap.put(10, null); //java.lang.NullPointerException
cmap.put(10, "hai");
System.out.println(cmap);

Hashtable<Integer, String> ht = new Hashtable(); // Null is not allowing for K,V
//ht.put(null, null); //java.lang.NullPointerException
//ht.put(10, null);    //java.lang.NullPointerException
System.out.println(ht);
⚠️ **GitHub.com Fallback** ⚠️