Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, September 4, 2017

Java - Stack Class

Source Link:
https://www.tutorialspoint.com/java/util/java_util_stack.htm

Some Useful Methods:

boolean empty()
This method tests if this stack is empty.

E peek()
This method looks at the object at the top of this stack without removing it from the stack.

E pop()
This method removes the object at the top of this stack and returns that object as the value of this function.

E push(E item)
This method pushes an item onto the top of this stack.

int search(Object o)
This method returns the 1-based position where an object is on this stack.

Example:
package com.tutorialspoint;
import java.util.*;
public class StackDemo {
   public static void main(String args[]) {
   // creating stack
   Stack st = new Stack();
      
   // populating stack
   st.push("Java");
   st.push("Source");
   st.push("code");
      
   // checking the top object
   System.out.println("Top object is: "+st.peek());
   }     
}
Let us compile and run the above program, this will produce the following result.
Top object is: code 

Java - PriorityQueue Class

Source Link:
https://www.tutorialspoint.com/java/util/java_util_priorityqueue.htm

Some Useful Methods:

boolean add(E e)
This method inserts the specified element into this priority queue.

void clear()
This method removes all of the elements from this priority queue.

boolean contains(Object o)
This method returns true if this queue contains the specified element.

boolean offer(E e)
This method inserts the specified element into this priority queue.

E peek()
This method retrieves, but does not remove, the head of this queue, or returns null if this queue is empty.

E poll()
This method retrieves and removes the head of this queue, or returns null if this queue is empty.

boolean remove(Object o)
This method removes a single instance of the specified element from this queue, if it is present.

int size()
This method returns the number of elements in this collection.

Object[] toArray()
This method returns an array containing all of the elements in this queue.

Example: 
package com.tutorialspoint;
public class PriorityQueueDemo {
   public static void main(String args[]) {
   // create priority queue
   PriorityQueue < Integer >  prq = new PriorityQueue < Integer > (); 
       
   // insert values in the queue
   prq.add(6);  
   prq.add(9);
   prq.add(5);
   prq.add(64);
   prq.add(6);
      
   System.out.println ( "Priority queue values are: "+ prq);
      
   // get objects from the queue
   Object[] arr = prq.toArray(); 
  
   System.out.println ( "Value in array: ");
      
   for ( int i = 0; i<arr.length; i++ ){  
   System.out.println ( "Value: " + arr[i].toString()) ; 
   }
   }
}
Let us compile and run the above program, this will produce the following result.
Priority queue values are: [5, 6, 6, 64, 9]
Value in array: 
Value: 5
Value: 6
Value: 6
Value: 64
Value: 9 

Java - Queue Interface

Source Link:
https://stackoverflow.com/questions/4626812/how-do-i-instantiate-a-queue-object-in-java

Notes:
1. Queue in Java is defined as an interface.
2. Many ready-to-use implementation (is present as part of JDK release)
3. Here are some: LinkedList, Priority Queue, ArrayBlockingQueue, etc.

Example: 
import java.util.LinkedList; 
import java.util.Queue;
public class QueueExample {
 public static void main (String[] args) 
  Queue que = new LinkedList(); 
  que.add("first");
  que.offer("second");
  que.offer("third");
  System.out.println("Queue Print:: " + que);

  String head = que.element();
  System.out.println("Head element:: " + head);

  String element1 = que.poll();
  System.out.println("Removed Element:: " + element1);

  System.out.println("Queue Print after poll:: " + que);
  String element2 = que.remove();
  System.out.println("Removed Element:: " + element2);

  System.out.println("Queue Print after remove:: " + que);  
 }
} 
some more notes: 
1. The add and offer methods have the same semantics. 
2. The remove() and poll() methods differ only in their behavior when the queue is empty. 
3. The remove() method throws an exception, while the poll() method returns null.

Sunday, September 3, 2017

Java - List Interface

Source Link:
https://www.tutorialspoint.com/java/java_list_interface.htm

Some Useful Methods:

void add(int index, Object obj)
Inserts obj into the invoking list at the index passed in the index. Any pre-existing elements at or beyond the point of insertion are shifted up. Thus, no elements are overwritten.

Object get(int index)
Returns the object stored at the specified index within the invoking collection.

int indexOf(Object obj)
Returns the index of the first instance of obj in the invoking list. If obj is not an element of the list, .1 is returned.

int lastIndexOf(Object obj)
Returns the index of the last instance of obj in the invoking list. If obj is not an element of the list, .1 is returned.

Object remove(int index)
Removes the element at position index from the invoking list and returns the deleted element. The resulting list is compacted. That is, the indexes of subsequent elements are decremented by one.

Object set(int index, Object obj)
Assigns obj to the location specified by index within the invoking list.

List subList(int start, int end)
Returns a list that includes elements from start to end.1 in the invoking list. Elements in the returned list are also referenced by the invoking object.

Example: 
import java.util.*;
public class CollectionsDemo {
   public static void main(String[] args) {
      List a1 = new ArrayList();
      a1.add("Zara");
      a1.add("Mahnaz");
      a1.add("Ayan");      
      System.out.println(" ArrayList Elements");
      System.out.print("\t" + a1);

      List l1 = new LinkedList();
      l1.add("Zara");
      l1.add("Mahnaz");
      l1.add("Ayan");
      System.out.println();
      System.out.println(" LinkedList Elements");
      System.out.print("\t" + l1);
   }
}
This will produce the following result − 
ArrayList Elements 
 [Zara, Mahnaz, Ayan] 
LinkedList Elements 
 [Zara, Mahnaz, Ayan]

Java - Map Interface

Source Link:
https://www.tutorialspoint.com/java/java_map_interface.htm

Some Useful Methods:

void clear( )
Removes all key/value pairs from the invoking map.

boolean containsKey(Object k)
Returns true if the invoking map contains k as a key. Otherwise, returns false.

boolean containsValue(Object v)
Returns true if the map contains v as a value. Otherwise, returns false.

Object get(Object k)
Returns the value associated with the key k.

boolean isEmpty( )
Returns true if the invoking map is empty. Otherwise, returns false.

Set keySet( )
Returns a Set that contains the keys in the invoking map. This method provides a set-view of the keys in the invoking map.

Object put(Object k, Object v)
Puts an entry in the invoking map, overwriting any previous value associated with the key. The key and value are k and v, respectively. Returns null if the key did not already exist. Otherwise, the previous value linked to the key is returned.

Object remove(Object k)
Removes the entry whose key equals k.

int size( )
Returns the number of key/value pairs in the map.

Example: 
import java.util.*; 
public class CollectionsDemo {
   public static void main(String[] args) {
      Map m1 = new HashMap(); 
      m1.put("Zara", "8");
      m1.put("Mahnaz", "31");
      m1.put("Ayan", "12");
      m1.put("Daisy", "14");

      System.out.println();
      System.out.println(" Map Elements");
      System.out.print("\t" + m1);
   }
}
This will produce the following result − 
Map Elements
 {Daisy = 14, Ayan = 12, Zara = 8, Mahnaz = 31}

Java - Set Interface

Source Link:
https://www.tutorialspoint.com/java/java_set_interface.htm

Some Useful Methods:

add( )
Adds an object to the collection.

clear( )
Removes all objects from the collection.

contains( )
Returns true if a specified object is an element within the collection.

isEmpty( )
Returns true if the collection has no elements.

remove( )
Removes a specified object from the collection.

size( )
Returns the number of elements in the collection.

Example: 
import java.util.*;
public class SetDemo {

  public static void main(String args[]) { 
      int count[] = {34, 22,10,60,30,22};
      Set<Integer> set = new HashSet<Integer>();
      try {
         for(int i = 0; i < 5; i++) {
            set.add(count[i]);
         }
         System.out.println(set);
         TreeSet sortedSet = new TreeSet<Integer>(set);
         System.out.println("The sorted list is:");
         System.out.println(sortedSet);

         System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());
         System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());
      }
      catch(Exception e) {}
   }
} 
This will produce the following result − 
[34, 22, 10, 60, 30] 
The sorted list is: 
[10, 22, 30, 34, 60] 
The First element of the set is: 10 
The last element of the set is: 60

Java - Math Class

Source Link:
https://www.tutorialspoint.com/java/lang/java_lang_math.htm

Some Useful Methods:

static int abs(int a) 
This method returns the absolute value of an int value.

static double abs(double a)
This method returns the absolute value of a double value.

static double ceil(double a)
This method returns the smallest (closest to negative infinity) double value that is greater than or equal to the argument and is equal to a mathematical integer.

static double floor(double a)
This method returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.

static int round(float a)
This method returns the closest int to the argument.
 
static double max(double a, double b)
This method returns the greater of two double values.

static int max(int a, int b)
This method returns the greater of two int values.

static double min(double a, double b)
This method returns the smaller of two double values.

static int min(int a, int b)
This method returns the smaller of two int values.

static double pow(double a, double b)
This method returns the value of the first argument raised to the power of the second argument.
 
static double sqrt(double a)
This method returns the correctly rounded positive square root of a double value.

Example:
package com.tutorialspoint;
import java.lang.*;
public class MathDemo {
   public static void main(String[] args) {
      // get two double numbers
      double x = 60984.1;
      double y = -497.99;
      // call floor and print the result
      System.out.println("Math.floor(" + x + ")=" + Math.floor(x));
      System.out.println("Math.floor(" + y + ")=" + Math.floor(y));
      System.out.println("Math.floor(0)=" + Math.floor(0));
   }
}
Let us compile and run the above program, this will produce the following result −
Math.floor(60984.1)=60984.0 
Math.floor(-497.99)=-498.0 
Math.floor(0)=0.0

Java - StringBuilder Class

Source Link:
https://www.tutorialspoint.com/java/lang/java_lang_stringbuilder.htm

Some Useful Methods:

StringBuilder append(Object obj)
This method appends the string representation of the Object argument.

char charAt(int index)
This method returns the char value in this sequence at the specified index.

StringBuilder delete(int start, int end)
This method removes the characters in a substring of this sequence.

StringBuilder deleteCharAt(int index)
This method removes the char at the specified position in this sequence.

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Characters are copied from this sequence into the destination character array dst.

int indexOf(String str)
This method returns the index within this string of the first occurrence of the specified substring.

StringBuilder insert(int offset, char c)
This method inserts the string representation of the char argument into this sequence.

StringBuilder insert(int offset, char[] str)
This method inserts the string representation of the char array argument into this sequence.

StringBuilder insert(int offset, Object obj)
This method inserts the string representation of the Object argument into this character sequence.

int length()
This method returns the length (character count).

StringBuilder replace(int start, int end, String str)
This method replaces the characters in a substring of this sequence with characters in the specified String.

StringBuilder reverse()
This method causes this character sequence to be replaced by the reverse of the sequence.

void setCharAt(int index, char ch)
Character at the specified index is set to ch.

String substring(int start, int end)
This method returns a new String that contains a subsequence of characters currently contained in this sequence.

String toString()
This method returns a string representing the data in this sequence.

Example: 
package com.tutorialspoint;
import java.lang.*;
public class StringBuilderDemo {
   public static void main(String[] args) {
  
      StringBuilder str = new StringBuilder("india");
      System.out.println("string = " + str);

      // reverse characters of the StringBuilder and prints it
      System.out.println("reverse = " + str.reverse());
  
      // reverse is equivalent to the actual
      str = new StringBuilder("malayalam");
      System.out.println("string = " + str);
 
      // reverse characters of the StringBuilder and prints it
      System.out.println("reverse = " + str.reverse());
   }
}

Let us compile and run the above program, this will produce the following result −
string = india 
reverse = aidni 
string = malayalam 
reverse = malayalam

Java - Strings Class

Source Link:
https://www.tutorialspoint.com/java/java_strings.htm

Some Useful Methods:

char charAt(int index)
Returns the character at the specified index.

String concat(String str)
Concatenates the specified string to the end of this string.

boolean equals(Object anObject)
Compares this string to the specified object.

boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.

int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.

int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.

int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.

int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.

int length()
Returns the length of this string.

String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

String[] split(String regex)
Splits this string around matches of the given regular expression.

boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.

String substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.

char[] toCharArray()
Converts this string to a new character array.

String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.

String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.

String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.

Example:
import java.io.*;
public class Test {

   public static void main(String args[]) {
      String Str = new String("   Welcome to Tutorialspoint.com   ");

      System.out.print("Return Value :" );
      System.out.println(Str.trim() );
   }
}
This will produce the following result −
Return Value :Welcome to Tutorialspoint.com

Codility - Lesson 16 Greedy algorithms - 2. MaxNonoverlappingSegments

Source Link: https://app.codility.com/programmers/lessons/16-greedy_algorithms/max_nonoverlapping_segments/ Question: Located on a line ...