diff --git a/BarcodeGenerator.java b/BarcodeGenerator.java new file mode 100644 index 0000000..d8ce5ed --- /dev/null +++ b/BarcodeGenerator.java @@ -0,0 +1,27 @@ +/* + */ + +import java.util.Random; // make sure to write the import for Random class + +/** + * + * @author ahsan + */ +public class BarcodeGenerator +{ + public String generateBarcode() + { + String barcode; + String[] numbers={"0","1","2","3","4","5","6","7","8","9"}; + String[] Alphabets ={"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}; + Random random = new Random(); //creating instance of Random class + int n1=random.nextInt(10); // generating a random number + int n2=random.nextInt(10); + int n3=random.nextInt(10); + int n4=random.nextInt(10); + // now creating barcode using random numbers i-e n1, n2 + barcode= numbers[n1]+numbers[n2]+numbers[n3]+numbers[n4]; + return barcode; + } +} + diff --git a/CreatingStrings b/CreatingStrings new file mode 100644 index 0000000..9c57695 --- /dev/null +++ b/CreatingStrings @@ -0,0 +1,35 @@ +/* + this files helps you understand string and shows different ways of creating string + String in java is simply an object that refers to the array pf characters + +*/ +package strings; + +/** + * + * @author Ahsan Qadeer + */ +public class CreatingString { + + // ch and ahsan are same + char ch[]={'a','h','s','a','n'}; + String name="ahsan";// this is called string literal + // + String name2="ahsan";//this does'nt create a new literal + // name and name2 are refering to same array of characters in the stringConstantPool within memory + + String name3="ahsanqadeer";//new literal refering to a new string in string contant pool which resides in heap memory + + //other ways of creating strings + String s=new String("ahsan"); + // JVM will create a new string object in normal (non-pool) heap memory, and the literal "ahsan" will be placed in the string constant pool. + + String s2=new String("ahsan"); + // s1 and s2 don't have same reference; + public static void main(String[] args) { + // TODO code application logic here + CreatingString ct=new CreatingString(); + System.out.println(ct.name2==ct.name); + } + +} diff --git a/Data Structures & Algorithm/Sorting/Bitonic Sort.java b/Data Structures & Algorithm/Sorting/Bitonic Sort.java new file mode 100644 index 0000000..8e22f32 --- /dev/null +++ b/Data Structures & Algorithm/Sorting/Bitonic Sort.java @@ -0,0 +1,84 @@ +public class BitonicSort +{ + /* The parameter dir indicates the sorting direction, + ASCENDING or DESCENDING; if (a[i] > a[j]) agrees + with the direction, then a[i] and a[j] are + interchanged. */ + void compAndSwap(int a[], int i, int j, int dir) + { + if ( (a[i] > a[j] && dir == 1) || + (a[i] < a[j] && dir == 0)) + { + // Swapping elements + int temp = a[i]; + a[i] = a[j]; + a[j] = temp; + } + } + + /* It recursively sorts a bitonic sequence in ascending + order, if dir = 1, and in descending order otherwise + (means dir=0). The sequence to be sorted starts at + index position low, the parameter cnt is the number + of elements to be sorted.*/ + void bitonicMerge(int a[], int low, int cnt, int dir) + { + if (cnt>1) + { + int k = cnt/2; + for (int i=low; i1) + { + int k = cnt/2; + + // sort in ascending order since dir here is 1 + bitonicSort(a, low, k, 1); + + // sort in descending order since dir here is 0 + bitonicSort(a,low+k, k, 0); + + // Will merge wole sequence in ascending order + // since dir=1. + bitonicMerge(a, low, cnt, dir); + } + } + + /*Caller of bitonicSort for sorting the entire array + of length N in ASCENDING order */ + void sort(int a[], int N, int up) + { + bitonicSort(a, 0, N, up); + } + + /* A utility function to print array of size n */ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i= 0; i--) + heapify(arr, n, i); + + // One by one extract an element from heap + for (int i = n - 1; i > 0; i--) { + // Move current root to end + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + + // call max heapify on the reduced heap + heapify(arr, i, 0); + } + } + + // To heapify a subtree rooted with node i which is + // an index in arr[]. n is size of heap + void heapify(int arr[], int n, int i) { + int largest = i; // Initialize largest as root + int l = 2 * i + 1; // left = 2*i + 1 + int r = 2 * i + 2; // right = 2*i + 2 + // If left child is larger than root + if (l < n && arr[l] > arr[largest]) largest = l; + + // If right child is larger than largest so far + if (r < n && arr[r] > arr[largest]) largest = r; + + // If largest is not root + if (largest != i) { + int swap = arr[i]; + arr[i] = arr[largest]; + arr[largest] = swap; + + // Recursively heapify the affected sub-tree + heapify(arr, n, largest); + } + } + + /* A utility function to print array of size n */ + static void printArray(int arr[]) { + int n = arr.length; + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + " "); + System.out.println(); + } + + // Driver program + public static void main(String args[]) { + int arr[] = { + 12, + 11, + 13, + 5, + 6, + 7 + }; + int n = arr.length; + + HeapSort ob = new HeapSort(); + ob.sort(arr); + + System.out.println("Sorted array is"); + printArray(arr); + } +} diff --git a/Data Structures & Algorithm/Sorting/Radix.Java b/Data Structures & Algorithm/Sorting/Radix.Java new file mode 100644 index 0000000..ab7b9f0 --- /dev/null +++ b/Data Structures & Algorithm/Sorting/Radix.Java @@ -0,0 +1,120 @@ +import java.io. * ; + +import java.util. * ; + +class Radix { + + // A utility function to get maximum value in arr[] + static int getMax(int arr[], int n) + + { + + int mx = arr[0]; + + for (int i = 1; i < n; i++) + + if (arr[i] > mx) + + mx = arr[i]; + + return mx; + + } + + // A function to do counting sort of arr[] according to + // the digit represented by exp. + static void countSort(int arr[], int n, int exp) + + { + + int output[] = new int[n]; // output array + int i; + + int count[] = new int[10]; + + Arrays.fill(count, 0); + + // Store count of occurrences in count[] + for (i = 0; i < n; i++) + + count[(arr[i] / exp) % 10]++; + + // Change count[i] so that count[i] now contains + // actual position of this digit in output[] + for (i = 1; i < 10; i++) + + count[i] += count[i - 1]; + + // Build the output array + for (i = n - 1; i >= 0; i--) { + + output[count[(arr[i] / exp) % 10] - 1] = arr[i]; + + count[(arr[i] / exp) % 10]--; + + } + + // Copy the output array to arr[], so that arr[] now + // contains sorted numbers according to curent digit + for (i = 0; i < n; i++) + + arr[i] = output[i]; + + } + + // The main function to that sorts arr[] of size n using + // Radix Sort + static void radixsort(int arr[], int n) + + { + + // Find the maximum number to know number of digits + int m = getMax(arr, n); + + // Do counting sort for every digit. Note that + // instead of passing digit number, exp is passed. + // exp is 10^i where i is current digit number + for (int exp = 1; m / exp > 0; exp *= 10) + + countSort(arr, n, exp); + + } + + // A utility function to print an array + static void print(int arr[], int n) + + { + + for (int i = 0; i < n; i++) + + System.out.print(arr[i] + " "); + + } + + /*Driver Code*/ + + public static void main(String[] args) + + { + + int arr[] = { + 170, + 45, + 75, + 90, + 802, + 24, + 2, + 66 + }; + + int n = arr.length; + + // Function Call + radixsort(arr, n); + + print(arr, n); + + } + +} diff --git a/Downcasting.java b/Downcasting.java new file mode 100644 index 0000000..64e2b6f --- /dev/null +++ b/Downcasting.java @@ -0,0 +1,34 @@ + +// Downcasting is when a child class type reference variable point to/references +// to a parent object or parentclass type +package downcasting; + +class Animal +{ + +} +public class Downcasting extends Animal{ + + + static void method(Animal a) { + if(a instanceof Downcasting){ + Downcasting d=(Downcasting)a;//downcasting + System.out.println("ok downcasting performed"); + } + } + + public static void main(String[] args) { + + //downcasting is not possible in this way will give compile-time error + // Downcasting d=new Animal(); + + //Compiles successfully but ClassCastException is thrown at runtime if we use type casting as shown under : + // Dog d=(Dog)new Animal(); + + //but we can do it as under + Animal a=new Downcasting(); + Downcasting.method(a); + + } + +} diff --git a/Enum/.idea/.gitignore b/Enum/.idea/.gitignore new file mode 100644 index 0000000..597a708 --- /dev/null +++ b/Enum/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Datasource local storage ignored files +/../../../../:\hacktoberfestProject\Enum\.idea/dataSources/ +/dataSources.local.xml +# Editor-based HTTP Client requests +/httpRequests/ diff --git a/Enum/.idea/misc.xml b/Enum/.idea/misc.xml new file mode 100644 index 0000000..0548357 --- /dev/null +++ b/Enum/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Enum/.idea/modules.xml b/Enum/.idea/modules.xml new file mode 100644 index 0000000..ff13c54 --- /dev/null +++ b/Enum/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/Enum/Enum.iml b/Enum/Enum.iml new file mode 100644 index 0000000..c90834f --- /dev/null +++ b/Enum/Enum.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Enum/src/EnumDemo.java b/Enum/src/EnumDemo.java new file mode 100644 index 0000000..2fcbb3c --- /dev/null +++ b/Enum/src/EnumDemo.java @@ -0,0 +1,37 @@ +/** + * Enum is used for define constant or final variables. + */ + +public class EnumDemo { + + enum TASK_STATUS{ + TODO, + IN_PROGRESS, + REVIEW, + DONE + } + + public static void main(String[] args) { + printStatusOfTheTask(TASK_STATUS.TODO); + printStatusOfTheTask(TASK_STATUS.DONE); + printStatusOfTheTask(TASK_STATUS.IN_PROGRESS); + printStatusOfTheTask(TASK_STATUS.REVIEW); + } + + private static void printStatusOfTheTask(TASK_STATUS status){ + switch (status) { + case TODO: + System.out.printf("Task is still TODO, and anyone can assign it.\n"); + break; + case IN_PROGRESS: + System.out.printf("Task is in progress, hopefully, development is finish soon.\n"); + break; + case REVIEW: + System.out.println("Development is finished and ready for QA testing.\n"); + break; + case DONE: + System.out.printf("Tasks is finished successfully.\n"); + break; + } + } +} diff --git a/ExceptionHandling/ArrayIndexOutOfBound.java b/ExceptionHandling/ArrayIndexOutOfBound.java new file mode 100644 index 0000000..faaebfe --- /dev/null +++ b/ExceptionHandling/ArrayIndexOutOfBound.java @@ -0,0 +1,15 @@ +// built-in Exception of ArrayIndexOutOfBound + +public class ArrayIndexOutOfBound +{ + public static void main(String args[]) + { + try{ + int a[] = new int[5]; + a[6] = 9; + } + catch(ArrayIndexOutOfBoundsException e){ + System.out.println ("Array Index is Out Of Bounds"); + } + } +} \ No newline at end of file diff --git a/ExceptionHandling/priceException.java b/ExceptionHandling/priceException.java new file mode 100755 index 0000000..fe3479f --- /dev/null +++ b/ExceptionHandling/priceException.java @@ -0,0 +1,18 @@ +class InvalidPriceException extends Exception{ + InvalidPriceException(String s){ + super(s); + } +} +class TestCustomException1{ +static void validate(int price)throws InvalidPriceException{ +if(price<0) +throw new InvalidPriceException(price+" is Invalid Price"); +else +System.out.println(price +" is valid price"); +} +public static void main(String args[]){ +try{ +validate(-2); } +catch(Exception m){System.out.println("Exception occured: "+m);} +} +} diff --git a/FileOperation/.idea/.gitignore b/FileOperation/.idea/.gitignore new file mode 100644 index 0000000..c89c3b7 --- /dev/null +++ b/FileOperation/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Datasource local storage ignored files +/../../../../:\hacktoberfestProject\FileOperation\.idea/dataSources/ +/dataSources.local.xml +# Editor-based HTTP Client requests +/httpRequests/ diff --git a/FileOperation/.idea/misc.xml b/FileOperation/.idea/misc.xml new file mode 100644 index 0000000..0548357 --- /dev/null +++ b/FileOperation/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/FileOperation/.idea/modules.xml b/FileOperation/.idea/modules.xml new file mode 100644 index 0000000..29a50a8 --- /dev/null +++ b/FileOperation/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/FileOperation/FileOperation.iml b/FileOperation/FileOperation.iml new file mode 100644 index 0000000..c90834f --- /dev/null +++ b/FileOperation/FileOperation.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/FileOperation/src/FileOperationDemo.java b/FileOperation/src/FileOperationDemo.java new file mode 100644 index 0000000..8ee8b09 --- /dev/null +++ b/FileOperation/src/FileOperationDemo.java @@ -0,0 +1,83 @@ +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Scanner; + +public class FileOperationDemo { + + public static void main(String[] args) { + File profileFile = createAndWrite(); + if (profileFile == null) { + return; + } + List dataList = readFile(profileFile); + if (dataList == null) { + return; + } + for (String data : dataList) { + System.out.printf(data); + } + //first comment below line (deletefile) , u can see profile.txt is creating in project directory. + deleteFile(profileFile); + } + + /** + * Reading file and getting data as string array. + * + * @param file - send file which u want to read + * @return - file content as string + */ + private static List readFile(File file) { + try { + List data = new ArrayList(); + Scanner scanner = new Scanner(file); + while (scanner.hasNextLine()) { + data.add(scanner.nextLine()); + } + scanner.close(); + return data; + } catch (FileNotFoundException e) { + System.out.println(e.getMessage()); + e.printStackTrace(); + } + return null; + } + + /** + * creating file and writing string to file + * + * @return + */ + private static File createAndWrite() { + try { + //Creating file + File file = new File("profile.txt"); + + //adding string data file + FileWriter fileWriter = new FileWriter("profile.txt"); + fileWriter.write("My Name is Bingo.\n"); + fileWriter.write("My Age is 20."); + fileWriter.close(); + return file; + } catch (IOException ioException) { + System.out.printf(ioException.getMessage()); + ioException.printStackTrace(); + } + return null; + } + + /** + * delete the file + * @param file - send file which u want to delete + */ + private static void deleteFile(File file) { + if (file.delete()) { + System.out.println("Deleted the file: " + file.getName() + " successfully."); + } else { + System.out.println("Failed to delete the file: " + file.getName()); + } + } +} diff --git a/Java Array/Example4.java b/Java Array/Example4.java new file mode 100644 index 0000000..f29af6d --- /dev/null +++ b/Java Array/Example4.java @@ -0,0 +1,20 @@ +// in this program we are passing an array to a method to calculate the sum of elements of Array +class Arrays +{ + public static void main(String args[]) + { + int arr[] = {3, 1, 2, 5, 4}; + // method to which an array is being passed + sum(arr); + + } + public static void sum(int[] arr) + { + //initializing a variable to sum up all the elements or array + int sum = 0; + // for loop to calculate the sum of elements + for (int i = 0; i < arr.length; i++) + sum+=arr[i]; + System.out.println("sum of array values : " + sum); + } +} \ No newline at end of file diff --git a/Java Inheritance/inheritance Example.java b/Java Inheritance/inheritance Example.java new file mode 100755 index 0000000..6899d75 --- /dev/null +++ b/Java Inheritance/inheritance Example.java @@ -0,0 +1,34 @@ +class BaseDemo{ + int a=1,b=2; +public BaseDemo(){ +} +BaseDemo(int c, int d){ + a=c; + b=d; +} +public void show(){ + System.out.print(a+" "+b); + System.out.print("Base class"); +} +} +class subclassdemo extends BaseDemo{ +subclassdemo(){ + super(2,3); +} +public void show(){ +System.out.print(a+" "+b); +System.out.print("Subclass and also overridden method"); +} +} +class test{ +public static void main(String arg[]){ +BaseDemo ob=new BaseDemo(); +BaseDemo ob2=new BaseDemo(5,6); +subclassdemo ob1=new subclassdemo(); +ob.show(); +System.out.println(); +ob1.show(); +System.out.println(); +ob2.show(); +} +} \ No newline at end of file diff --git a/Lamda/.idea/.gitignore b/Lamda/.idea/.gitignore new file mode 100644 index 0000000..f3abc05 --- /dev/null +++ b/Lamda/.idea/.gitignore @@ -0,0 +1,8 @@ +# Default ignored files +/shelf/ +/workspace.xml +# Datasource local storage ignored files +/../../../../:\hacktoberfestProject\Lamda\.idea/dataSources/ +/dataSources.local.xml +# Editor-based HTTP Client requests +/httpRequests/ diff --git a/Lamda/.idea/misc.xml b/Lamda/.idea/misc.xml new file mode 100644 index 0000000..0548357 --- /dev/null +++ b/Lamda/.idea/misc.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/Lamda/.idea/modules.xml b/Lamda/.idea/modules.xml new file mode 100644 index 0000000..66304bb --- /dev/null +++ b/Lamda/.idea/modules.xml @@ -0,0 +1,8 @@ + + + + + + + + \ No newline at end of file diff --git a/Lamda/Lamda.iml b/Lamda/Lamda.iml new file mode 100644 index 0000000..c90834f --- /dev/null +++ b/Lamda/Lamda.iml @@ -0,0 +1,11 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/Lamda/src/Employee.java b/Lamda/src/Employee.java new file mode 100644 index 0000000..2514fea --- /dev/null +++ b/Lamda/src/Employee.java @@ -0,0 +1,71 @@ +public class Employee { + + public static final String SINGLE = "SINGLE"; + public static final String MARRIED = "MARRIED"; + + private int employeeNumber; + private String name; + private int age; + private String status; + private double salary; + + public double getSalary() { + return salary; + } + + public void setSalary(double salary) { + this.salary = salary; + } + + public static String getSINGLE() { + return SINGLE; + } + + public static String getMARRIED() { + return MARRIED; + } + + public int getEmployeeNumber() { + return employeeNumber; + } + + public void setEmployeeNumber(int employeeNumber) { + this.employeeNumber = employeeNumber; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getStatus() { + return status; + } + + public void setStatus(String status) { + this.status = status; + } + + @Override + public String toString() { + return "Person{" + + "personNumber=" + employeeNumber + + ", name='" + name + '\'' + + ", age=" + age + + ", status='" + status + '\'' + + ", salary='" + salary + '\'' + + '}'; + } + +} diff --git a/Lamda/src/EmployeeComparator.java b/Lamda/src/EmployeeComparator.java new file mode 100644 index 0000000..f88533f --- /dev/null +++ b/Lamda/src/EmployeeComparator.java @@ -0,0 +1,14 @@ +import java.util.Comparator; + +public class EmployeeComparator implements Comparator { + @Override + public int compare(Employee e1, Employee e2) { + if (e1.getEmployeeNumber() < e2.getEmployeeNumber()) { + return -1; + } else if (e1.getEmployeeNumber() > e2.getEmployeeNumber()) { + return 1; + } else { + return 0; + } + } +} diff --git a/Lamda/src/EmployeeDataLoader.java b/Lamda/src/EmployeeDataLoader.java new file mode 100644 index 0000000..10b5763 --- /dev/null +++ b/Lamda/src/EmployeeDataLoader.java @@ -0,0 +1,60 @@ +import java.util.ArrayList; +import java.util.List; + +public class EmployeeDataLoader { + public static List getEmployeeList() + { + Employee e1 = new Employee(); + e1.setEmployeeNumber(1); + e1.setName("Dileepa"); + e1.setAge(28); + e1.setStatus(Employee.SINGLE); + e1.setSalary(190.00); + + Employee e2 = new Employee(); + e2.setEmployeeNumber(2); + e2.setName("Madawa"); + e2.setAge(28); + e2.setStatus(Employee.SINGLE); + e2.setSalary(150.00); + + Employee e3 = new Employee(); + e3.setEmployeeNumber(3); + e3.setName("Janaki"); + e3.setAge(30); + e3.setStatus(Employee.SINGLE); + e3.setSalary(120.00); + + Employee e4 = new Employee(); + e4.setEmployeeNumber(4); + e4.setName("Tharindu"); + e4.setAge(30); + e4.setStatus(Employee.MARRIED); + e4.setSalary(100.00); + + Employee e5 = new Employee(); + e5.setEmployeeNumber(5); + e5.setName("Umesh"); + e5.setAge(32); + e5.setStatus(Employee.MARRIED); + e5.setSalary(110.00); + + Employee e6 = new Employee(); + e6.setEmployeeNumber(6); + e6.setName("Tharani"); + e6.setAge(27); + e6.setStatus(Employee.SINGLE); + e6.setSalary(100.00); + + List employees = new ArrayList(); + employees.add(e1); + employees.add(e2); + employees.add(e3); + employees.add(e4); + employees.add(e5); + employees.add(e6); + return employees; + } + + +} diff --git a/Lamda/src/StreamFilterDemo.java b/Lamda/src/StreamFilterDemo.java new file mode 100644 index 0000000..59b7f88 --- /dev/null +++ b/Lamda/src/StreamFilterDemo.java @@ -0,0 +1,109 @@ +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +public class StreamFilterDemo { + public static void main(String[] args) { + + List employeeList = EmployeeDataLoader.getEmployeeList(); + Stream stream = employeeList.stream(); + + /** + * meaning of Integer::new -> (value) -> new Integer(value) + * meaning of Employee::getName -> (employee) -> employee.getName() + */ + + /**Apply Filter extract results to list.**/ + Predicate singleEmployeePredicate = employee -> employee.getStatus().equals(Employee.SINGLE); + List singleList = stream.filter(singleEmployeePredicate).collect(Collectors.toList()); + singleList.forEach(sing -> System.out.println(sing.toString())); + + //How to use allMatch, anyMatch and noneMatch + /** + * Stream.allMatch -> That predicate is applied to each element of stream and if each and every element satisfies the predicate then it returns true otherwise false. + * Stream.anyMatch -> The element of stream is iterated for this predicate. If any element matches then it returns true otherwise false. + * Stream.noneMatch -> NoneMatch method is a method which takes argument as a predicate and if none of element of stream matches the predicate, then it returns true else false. + */ + Stream stream1 = employeeList.stream(); + Predicate employeeNumberGreaterThan = employee -> employee.getEmployeeNumber() > 1; + boolean allMatch = stream1.allMatch(employeeNumberGreaterThan); + Stream stream2 = employeeList.stream(); + boolean anyMatch = stream2.anyMatch(employeeNumberGreaterThan); + Stream stream3 = employeeList.stream(); + boolean noneMatch = stream3.noneMatch(employeeNumberGreaterThan); + System.out.println("AllMatch -> {" + allMatch + "}, AnyMatch -> {" + anyMatch + "}, NonMatch -> {" + noneMatch + "}"); + //out put AllMatch -> {false}, AnyMatch -> {true}, NonMatch -> {false} + + + //How to use findAny, findFirst, limit, max, min + + Stream stream4 = employeeList.stream(); + Optional findAny = stream4.filter(singleEmployeePredicate).findAny(); //Return Random Element from the Filtered Stream + Stream stream5 = employeeList.stream(); + Optional findFirst = stream5.filter(singleEmployeePredicate).findFirst(); //Return First Element from the Filtered Stream. + if (findAny.isPresent() && findFirst.isPresent() ) + { + Employee anyEmployee = findAny.get(); + Employee firstEmployee = findFirst.get(); + System.out.println( "Any Employee -> {" + anyEmployee +" }, First Employee -> { "+ firstEmployee+" }"); + + } + Stream stream6 = employeeList.stream(); + Stream stream7 = stream6.filter(singleEmployeePredicate).limit(10); + stream7.forEach(System.out::println); //limit method of stream API, returns stream instance with the given number of element in limit as an argument. + + //max method returns maximum element on the basis of given comparator. It returns Optional instance. + Optional max = employeeList.stream().filter(singleEmployeePredicate).max(new EmployeeComparator()); + //min method returns minimum element on the basis of given comparator. It returns Optional instance. + Optional min = employeeList.stream().filter(singleEmployeePredicate).min(new EmployeeComparator()); + if ( max.isPresent() && min.isPresent() ) + { + Employee maxEmployee = max.get(); + Employee minEmployee = min.get(); + System.out.println( "Max Employee -> {" + maxEmployee +" }, Min Employee -> { "+ minEmployee+" }"); + } + + //How to use count and distinct operations + long singleStateCount = employeeList.stream().filter(singleEmployeePredicate).count(); + System.out.println("Single Employees are -> " + singleStateCount); + Stream distinctStream = employeeList.stream().filter(singleEmployeePredicate).distinct(); + distinctStream.forEach(System.out::println); + + /** + * Reduce Functionality. + */ + Stream employeeNumberStream = employeeList.stream().map(Employee::getEmployeeNumber); + int sum = employeeNumberStream.mapToInt(Integer::new).sum(); //map to int use convert to integer list. + System.out.println("Sum of Passenger numbers -> { " + sum + "}"); + Stream employeeNumberStream1 = employeeList.stream().map(Employee::getEmployeeNumber); + Optional sumValue = employeeNumberStream1.reduce((x, y) -> x + y); // without initial value return optional + System.out.println(sumValue); + Stream employeeNumberStream2 = employeeList.stream().map(Employee::getEmployeeNumber); + long sumValue1 = employeeNumberStream2.reduce(0, (x, y) -> x + y); //initial value with is zero + System.out.println(sumValue1); + + //mapFunctionality + Stream passengerNames = employeeList.stream().map(Employee::getName); + passengerNames.forEach(System.out::println); + + //GroupBy Functionality. + //Grouping list by single married as a key. + Map> groupByStatus = employeeList.stream().collect(Collectors.groupingBy(Employee::getStatus)); + System.out.println(groupByStatus); + //Group list as single married as key and get salary for one shot against them. + Map salaryWithStatus = employeeList.stream().collect(Collectors.groupingBy(Employee::getStatus, Collectors.summingDouble(Employee::getSalary))); + System.out.println(salaryWithStatus); + //partition grouping salary ( if salary is greater than 120, is one partition) + Map> collect = employeeList.stream().collect(Collectors.partitioningBy(employee -> employee.getSalary() > 120)); + System.out.println(collect); + + //HashMap Operations + // Print the key value pair in one line. + //hm.forEach((k,v) -> System.out.println("key: "+k+" value:"+v)); + + } + +} diff --git a/Loops/For Loop/ForLoopExample1.java b/Loops/For Loop/ForLoopExample1.java new file mode 100644 index 0000000..461c8c2 --- /dev/null +++ b/Loops/For Loop/ForLoopExample1.java @@ -0,0 +1,9 @@ +//infinte loop + +public class InfiniteLoop { + public static void main(String args[]){ + for(int i=1; i>=1; i++){ + System.out.println("The value of i is: "+i); + } + } +} \ No newline at end of file diff --git a/Loops/For Loop/ForLoopExample2.java b/Loops/For Loop/ForLoopExample2.java new file mode 100644 index 0000000..f2b6ba7 --- /dev/null +++ b/Loops/For Loop/ForLoopExample2.java @@ -0,0 +1,11 @@ + +// this is used to itterate through the array + +public class ForLoopExample3 { + public static void main(String args[]){ + int arr[]={9,3,4,1,10,24}; + for(int i=0; i') +ch1[i]='V'; +else if(ch1[i]=='<') +ch1[i]='W'; +else if(ch1[i]=='{') +ch1[i]='X'; +else if(ch1[i]=='}') +ch1[i]='Y'; +else if(ch1[i]=='[') +ch1[i]='Z'; +else if(ch1[i]=='_') +ch1[i]=' '; +} +str3=str3.copyValueOf(ch1); +t4.setText(str3); +} +if(e.getSource()==bt4){ +f1.show(); +f4.show(false); } +if(e.getSource()==b4) +System.exit(0); +} +} +class Project{ +public static void main(String arg[]){ +ED bt=new ED(); +} +} diff --git a/RealLifeExample.java b/RealLifeExample.java new file mode 100644 index 0000000..3b2e3ca --- /dev/null +++ b/RealLifeExample.java @@ -0,0 +1,37 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package reallifeecample; + +class Person +{ + String name; + int id; + Person (String name, int id) + { + this.id=id; + this.name=name; + } +} +class Emp extends Person +{ + double salary; + Emp (String name, int id, double salary) + { + super(name,id); + this.salary=salary; + } + void display() + { + System.out.println("id: "+id+", name: "+name+", salary: "+salary); + } +} +public class RealLifeExample { + static public void main (String[] args) + { + Emp obj=new Emp("Ahsan",26,100000.0); + obj.display(); + } +} diff --git a/WrapperClass.java b/WrapperClass.java new file mode 100644 index 0000000..640e1b4 --- /dev/null +++ b/WrapperClass.java @@ -0,0 +1,31 @@ +/* + Java is not 100% OOP because it can have primitive type variables like int float etc + but wrappper class gives a solution. instead of creating primitive variables. we can store our +data into wrapper classes. +for eg +Integer is a wrapper class which stores int values . But since Integer is a class not primitive variabele +hence we can say that now every things is object +*/ +package wrapper.pkgclass; + + +public class WrapperClass { + + public static void main(String[] args) { + // static function present in each wraper class + // takes input as integer and saves as integer + // return reference of Integer class + Integer in= Integer.valueOf("88"); + //similary + Float f=Float.valueOf("5.55"); + + //static funtion to convert string to corresponding types + int i=Integer.parseInt("22"); + //similarly + double d=Double.parseDouble("4.3"); + + //instance function that returns value stored in Integer class + int a =in.intValue(); + } + +}