import java.util.*;

import java.util.stream.*; 
import java.util.Map;
import java.util.Map.Entry;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Main {
    public static void main(String []args) {

//22) How do you find the most repeated element in an array?
  List<String> listOfStrings = Arrays.asList("Pen", "Eraser", "Note Book", "Pen", "Pencil", "Pen", "Note Book", "Pencil");
         
      /*  Map<String, Long> elementCountMap = listOfStrings.stream()
                                                         .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
       // Entry<String, Long> mostFrequent =  elementCountMap.entrySet().max(Map.Entry.comparingByValue()).get();
          
      //  Entry<String, Long> mostFrequentElement = elementCountMap.entrySet().stream().max(Map.Entry.comparingByValue()).get();
        Entry<String, Long> mostFrequentElement = elementCountMap.entrySet().stream().max(Map.Entry.comparingByValue()).get();
  
        System.out.println("Most Frequent Element : "+mostFrequentElement.getKey());
         
        System.out.println("Count : "+mostFrequentElement.getValue());*/
        
        List<String> listOfStrings = Arrays.asList("Pen", "Eraser", "Note Book", "Pen", "Pencil", "Pen", "Note Book", "Pencil");
         
        Map<String, Long> elementCountMap = listOfStrings.stream()
                                                         .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
         
        Entry<String, Long> mostFrequentElement = elementCountMap.entrySet().stream().max(Map.Entry.comparingByValue()).get();
         
        System.out.println("Most Frequent Element : "+mostFrequentElement.getKey());
         
        System.out.println("Count : "+mostFrequentElement.getValue());
//21) Print first 10 even numbers
//IntStream.rangeClosed(1, 10).map(i -> i * 2).forEach(System.out::println);
//IntStream.rangeClosed(1, 10).map(i -> i * 2).forEach(System.out::println);

 
 //20) Reverse an integer array
 
//int[] array = new int[] {5, 1, 7, 3, 9, 6};

       // int[] reversedArray = IntStream.rangeClosed(1, array.length).map(i -> array[array.length - i]).toArray();
         
      //  System.out.println(Arrays.toString(reversedArray));
        
         //20) Reverse an integer array without using new array
/* int[] array = new int[] {5, 1, 7, 3, 9, 6};
int startIndx = 0;
int endIndex=  array.length - 1;
while(startIndx < endIndex) {
   int temp = array[startIndx];
    array[startIndx] = array[endIndex] ;
    array[endIndex] = temp;
    startIndx ++;
    endIndex --;
}
 System.out.println(Arrays.toString(array));
*/

    //    int[] reversedArray = IntStream.rangeClosed(1, array.length).map(i -> array[array.length - i]).toArray();
        /* for(int i=0 ; i< array.length ; i++) {
           int temp = int[i];
           int[i] = int[length -1] ;
           int[length -1] = temp;
         }*/
      //  System.out.println(Arrays.toString(reversedArray));
                

// = IntStream.range(0, array.length).map(i -> array[array.length - i - 1]).toArray();
 //Arrays.stream(array).mapToObj(i -> array[array.length - i - 1]).forEach(System.out :: println);//map(i -> array[array.length - i - 1]).toArray();
//Arrays.stream(reverseArray).forEach(System.out :: println);

//Arrays.stream(reverseArray1).forEach(System.out :: println);
 //19) How do you find sum of first 10 natural numbers?
 
// System.out.println(IntStream.range(1,11).sum());
 
 
 //18) Reverse each word of a string using Java 8 streams?

/* String str = "Java Concept Of The Day";
 
 String reverseString = Arrays.stream(str.split(" ")).map(word -> new StringBuffer(word).reverse()).collect(Collectors.joining(" "));
 System.out.println(reverseString);
 */
// 17) How do you find common elements between two arrays?
   /*   List<Integer> list1 = Arrays.asList(71, 21, 34, 89, 56, 28);
         
        List<Integer> list2 = Arrays.asList(12, 56, 17, 21, 94, 34);
        
        list1.stream().filter(n -> list2.contains(n)).forEach(System.out :: println);
*/
 
 //16) Given an integer array, find sum and average of all elements?
       /* int[] a = new int[] {45, 12, 56, 15, 24, 75, 31, 89};
int sum = Arrays.stream(a).sum();
double avg = Arrays.stream(a).average();
System.out.println("sum"+sum);
System.out.println("avg"+avg);*/
 //15) Given a list of strings, sort them according to increasing order of their length?

  //List<String> listOfStrings = Arrays.asList("Java", "Python", "C#", "HTML", "Kotlin", "C++", "COBOL", "C");

 //listOfStrings.stream().sorted((p1, p2) -> p1.length().compareTo(p2.length())).forEach(System.out :: println);
  //listOfStrings.stream().sorted(Comparator.comparing(String::length)).forEach(System.out :: println);

// 14) Find second largest number in an integer array?

  /*  List<Integer> listOfIntegers = Arrays.asList(45, 12, 56, 15, 24, 75, 31, 89);

 Integer secondLargest = listOfIntegers.stream().sorted(Comparator.reverseOrder()).skip(1).findFirst().get();
System.out.println(secondLargest);*/
 //13) Find sum of all digits of a number in Java 8?
 
 /*Integer i =12345;
 
 Integer sumOfDigit = Stream.of(String.valueOf(i).split(""))
 //.mapToInt(Integer::valueOf).sum();
  .collect(Collectors.summingInt(Integer::valueOf));
System.out.println(sumOfDigit);*/

 
 //12) Java 8 program to check if two strings are anagrams or not?


 /* String s1 = "RaceCar";
        String s2 = "CarRace";
  s1 = Stream.of(s1.split("")).map(String::toUpperCase).sorted().collect(Collectors.joining());
   s2 = Stream.of(s2.split("")).map(String::toUpperCase).sorted().collect(Collectors.joining());
        if (s1.equals(s2)) 
        {
            System.out.println("Two strings are anagrams"+s1+s2);
        }
        else
        {
            System.out.println("Two strings are not anagrams");
        }
 */
 //11) How do you get three maximum numbers and three minimum numbers from the given list of integers?
/*
 List<Integer> listOfIntegers = Arrays.asList(45, 12, 56, 15, 24, 75, 31, 89);
 
 listOfIntegers.stream().sorted(Comparator.reverseOrder()).limit(3).forEach(System.out :: println);
 System.out.println("================");
 listOfIntegers.stream().sorted().limit(3).forEach(System.out::println);
*/
 
 //10) How do you merge two unsorted arrays into single sorted array without duplicates?

/* int[] a = new int[] {4, 2, 5, 5, 1};
         
        int[] b = new int[] {8, 1, 9, 5};

int[] c = IntStream.concat(Arrays.stream(a), Arrays.stream(b)).sorted().distinct().toArray();
 
  System.out.println(Arrays.toString(c));*/
 //9) How do you merge two unsorted arrays into single sorted array using Java 8 streams?

/* int[] a = new int[] {4, 2, 7, 1};
 int[] b = new int[] {8, 3, 9, 5};
 
 int[] c = IntStream.concat(Arrays.stream(a), Arrays.stream(b)).sorted().toArray();
   System.out.println(Arrays.toString(c));*/
   
   
// 8) Given a list of integers, find maximum and minimum of those numbers?

/* List<Integer> listOfIntegers = Arrays.asList(45, 12, 56, 15, 24, 75, 31, 89);

System.out.println(Collections.max(listOfIntegers));
System.out.println(Collections.min(listOfIntegers));*/


   
   
 //  7) From the given list of integers, print the numbers which are multiples of 5?
 
/* List<Integer> listOfIntegers = Arrays.asList(45, 12, 56, 15, 24, 75, 31, 89);
listOfIntegers.stream().filter( n -> n % 5 == 0).forEach(System.out :: println);

*/
   
   
  // 6) Given a list of strings, join the strings with ‘[‘ as prefix, ‘]’ as suffix and ‘,’ as delimiter?

       /* List<String> listOfStrings = Arrays.asList("Facebook", "Twitter", "YouTube", "WhatsApp", "LinkedIn");

   System.out.println(listOfStrings.stream().collect(Collectors.joining(",","[","]")));*/
   //5) How do you sort the given list of decimals in reverse order?

   // List<Double> decimalList = Arrays.asList(12.45, 23.58, 17.13, 42.89, 33.78, 71.85, 56.98, 21.12);
//decimalList.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);

  
   //4) How do you find frequency of each element in an array or a list?

/*List<String> stationeryList = Arrays.asList("Pen", "Eraser", "Note Book", "Pen", "Pencil", "Stapler", "Note Book", "Pencil");
Map<String, Long> mapElementFreq =stationeryList.stream()
              .collect(Collectors.groupingBy(
                Function.identity(), Collectors.counting()));
 
  mapElementFreq.entrySet().forEach(System.out::println);*/
   // frequency of each character in String
   
  /* String inputString = "abcdabdchabcdf";
  Map<Character, Long> mapCharFreq = inputString.chars()
  .mapToObj(c -> (char) c)
  .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    
    mapCharFreq.entrySet().forEach(System.out::println);*/
   // mapCharFreq.entryset().foreach((charater,frequency) -> System.out.println(charater + ":" + frequency));
   
   
   /* String [] stringArray ={"abc","pqr","abc","xyz","pqr"};
    System.out.println(Arrays.stream(stringArray).distinct().collect(Collectors.toList()));
    */
     /* List<String> listOfString = Arrays.asList("abc","pqr","abc","xyz","pqr");
      Set<String> setOfString =listOfString.stream().collect(Collectors.toSet());
      
      System.out.println(listOfString.toString());
      System.out.println(setOfString.toString());*/
      
      
       /* Integer[] integerArray = {1,2,3,4,5,6,7,8,9};

        Map<Boolean, List<Integer>> oddEvenMap = Arrays.stream(integerArray)
                .collect(Collectors.partitioningBy(num -> num % 2 == 0));

        System.out.println("even Numbers are: " + oddEvenMap.get(true));
        System.out.println("even Numbers are: " + oddEvenMap.get(false));*/
    }
} 

Java online compiler

Write, Run & Share Java code online using OneCompiler's Java online compiler for free. It's one of the robust, feature-rich online compilers for Java language, running the Java LTS version 17. Getting started with the OneCompiler's Java editor is easy and fast. The editor shows sample boilerplate code when you choose language as Java and start coding.

Taking inputs (stdin)

OneCompiler's Java online editor supports stdin and users can give inputs to the programs using the STDIN textbox under the I/O tab. Using Scanner class in Java program, you can read the inputs. Following is a sample program that shows reading STDIN ( A string in this case ).

import java.util.Scanner;
class Input {
    public static void main(String[] args) {
    	Scanner input = new Scanner(System.in);
    	System.out.println("Enter your name: ");
    	String inp = input.next();
    	System.out.println("Hello, " + inp);
    }
}

Adding dependencies

OneCompiler supports Gradle for dependency management. Users can add dependencies in the build.gradle file and use them in their programs. When you add the dependencies for the first time, the first run might be a little slow as we download the dependencies, but the subsequent runs will be faster. Following sample Gradle configuration shows how to add dependencies

apply plugin:'application'
mainClassName = 'HelloWorld'

run { standardInput = System.in }
sourceSets { main { java { srcDir './' } } }

repositories {
    jcenter()
}

dependencies {
    // add dependencies here as below
    implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.9'
}

About Java

Java is a very popular general-purpose programming language, it is class-based and object-oriented. Java was developed by James Gosling at Sun Microsystems ( later acquired by Oracle) the initial release of Java was in 1995. Java 17 is the latest long-term supported version (LTS). As of today, Java is the world's number one server programming language with a 12 million developer community, 5 million students studying worldwide and it's #1 choice for the cloud development.

Syntax help

Variables

short x = 999; 			// -32768 to 32767
int   x = 99999; 		// -2147483648 to 2147483647
long  x = 99999999999L; // -9223372036854775808 to 9223372036854775807

float x = 1.2;
double x = 99.99d;

byte x = 99; // -128 to 127
char x = 'A';
boolean x = true;

Loops

1. If Else:

When ever you want to perform a set of operations based on a condition If-Else is used.

if(conditional-expression) {
  // code
} else {
  // code
}

Example:

int i = 10;
if(i % 2 == 0) {
  System.out.println("i is even number");
} else {
  System.out.println("i is odd number");
}

2. Switch:

Switch is an alternative to If-Else-If ladder and to select one among many blocks of code.

switch(<conditional-expression>) {    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
...    
    
default:     
 //code to be executed when all the above cases are not matched;    
} 

3. For:

For loop is used to iterate a set of statements based on a condition. Usually for loop is preferred when number of iterations is known in advance.

for(Initialization; Condition; Increment/decrement){  
    //code  
} 

4. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while(<condition>){  
 // code 
}  

5. Do-While:

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {
  // code 
} while (<condition>); 

Classes and Objects

Class is the blueprint of an object, which is also referred as user-defined data type with variables and functions. Object is a basic unit in OOP, and is an instance of the class.

How to create a Class:

class keyword is required to create a class.

Example:

class Mobile {
    public:    // access specifier which specifies that accessibility of class members 
    string name; // string variable (attribute)
    int price; // int variable (attribute)
};

How to create a Object:

Mobile m1 = new Mobile();

How to define methods in a class:

public class Greeting {
    static void hello() {
        System.out.println("Hello.. Happy learning!");
    }

    public static void main(String[] args) {
        hello();
    }
}

Collections

Collection is a group of objects which can be represented as a single unit. Collections are introduced to bring a unified common interface to all the objects.

Collection Framework was introduced since JDK 1.2 which is used to represent and manage Collections and it contains:

  1. Interfaces
  2. Classes
  3. Algorithms

This framework also defines map interfaces and several classes in addition to Collections.

Advantages:

  • High performance
  • Reduces developer's effort
  • Unified architecture which has common methods for all objects.
CollectionDescription
SetSet is a collection of elements which can not contain duplicate values. Set is implemented in HashSets, LinkedHashSets, TreeSet etc
ListList is a ordered collection of elements which can have duplicates. Lists are classified into ArrayList, LinkedList, Vectors
QueueFIFO approach, while instantiating Queue interface you can either choose LinkedList or PriorityQueue.
DequeDeque(Double Ended Queue) is used to add or remove elements from both the ends of the Queue(both head and tail)
MapMap contains key-values pairs which don't have any duplicates. Map is implemented in HashMap, TreeMap etc.