Wednesday, December 23, 2015

How to request for CA marks manually

                                                                                                                             (Name),
                                                                                                                             (IT Number),
                                                                                                                              (Date).

Director,
Academic Affairs,

Dear Sir/Madam,

I have been registered as a prorata basis student. I sat for,

(What subjects you are decided to do
Eg:-
Probability and Statics
Software Engineering I )
Subjects as a second year student in 2014. The CA Mark I received is 45% for all subjects. So I hope to do only the final exam for those subjects. I kindly request you to convert my CA Marks to this year.
            Thank you,
                                                                                                         
   ……………………………………………
                                                                                             (Name)
                                                                                                                       (IT Number)



Tuesday, March 24, 2015

5 ways to Convert Java 8 Stream to List - Example, Tutorial

One of the common problem while working with Stream API in Java 8 is how to convert a Stream to List in Java because there is no toList() method present in Stream class. When you are processing a List using Stream's map and filter method, you ideally want your result in some collection so that you can pass it to other part of program. Though java.util.stream.Stream class has toArray() method to convert Stream to Array, but  there is no similar method to convert Stream to List or Set. Java has a design philosophy of providing conversion method between new and old API classes e.g. when they introduced Path class in JDK 7, which is similar to java.io.File, they provided a toPath() method to File class. Similarly they could have provided convenient methods like toList()toSet() into Stream class, but unfortunately they have not done that. Anyway, It seems they did thought about this and provided a class called Collector to collect the result of stream operations into different container or Collection classes. Here you will find methods like toList(), which can be used to convert Java 8 Stream to List. You can also use any List implementation class e.g. ArrayList or LinkedList to get contents of that Stream. I would have preferred having those method at-least the common ones directly into Stream but nevertheless there is something you can use to convert a Java 8 Stream to List. BTW, my research to this task also reveals several other way to achieve the same result, which I have summarized in this tutorial. If would suggest to prefer standard way, which is by using Stream.collect() and Collectors class, but its good to know other ways, just in case if you need.



Java 8 Stream to List conversion - 5 examples

Here are 5 simple ways to convert a Stream in Java 8 to List e.g. converting a Stream of String to a List of String, or converting a Stream of Integer to List of Integer and so on.


Using Collectors.toList() method
This is the standard way to collect the result of stream in a container e.g. List, Set or any Collection. Stream class has a collect() method which accepts a Collector and you can use Collectors.toList() method to collect the result in a List.

List listOfStream = streamOfString.collect(Collectors.toList());



Using Collectors.toCollection() method
This is actually generalization of previous method, here instead of creating List, you can collect elements of Stream in any Collection, including ArrayListLinkedList or any other List. In this example, we are collecting Stream elements into ArrayList.  The toColection() method returns a Collector that accumulates the input elements into a new Collection, in encounter order. The Collection is created by the provided Supplier instance, in this case we are usingArrayList::new, a constructor reference to collect them into ArrayList. You can also use lambda expression in place of method reference here, but method reference results in much more readable and concise code.

List listOfString  = streamOfString.collect(Collectors.toCollection(ArrayList::new));



Using forEach() method
You can also sue forEach() method to go through all element of Stream one by one and add them into a new List or ArrayList. This is simple, pragmatic approach, which beginners can use to learn.

Stream streamOfLetters = Stream.of("abc", "cde",
                "efg", "jkd", "res");
ArrayList list = new ArrayList<>();
streamOfLetters.forEach(list::add);



Using forEachOrdered method
This is extension of previous example, if Stream is parallel then elements may be processed out of order but if you want to add them into the same order they were present in Stream, you can use forEachOrdered() method. If you are not comfortable with forEach, I suggest look at this Stream tutorial to understand more.

Stream streamOfNumbers = Stream.of("one", "two",
                "three", "four", "five");
ArrayList myList = new ArrayList<>();
streamOfNumbers.parallel().forEachOrdered(myList::add);



Using toArray() method
Stream provides direct method to convert Stream to array, toArray(). The method which accepts no argument returns an object array as shown in our our sample program, but you can still get which type of array you want by using overloaded version of that method. Just like we have done in following example to create String array :

Stream streamOfShapes = Stream.of("Rectangle", "Square", "Circle", "Oval");
String[] arrayOfShapes = streamOfShapes.toArray(String[]::new);
List listOfShapes = Arrays.asList(arrayOfShapes);



Sample Program to convert Stream to List in Java 8

Java 8 Stream to List ExampleHere is the complete Java program to demonstrate all these five methods of converting Java 8 Streams to List. You can directly run them if you have installed JDK 8 in your machine. BTW, You should be using Netbeans with JDK 8 to code, compile and run Java program. The IDE has got excellent support and will help you to learn Java 8 quickly.
 
package test;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Java Program to convert Stream to List in Java 8
 *
 * @author Javin Paul
 */
public class Java8StreamToList{

    public static void main(String args[]) throws IOException {
        Stream<String> streamOfString = Stream.of("Java", "C++",
                "JavaScript", "Scala", "Python");

        // converting Stream to List using Collectors.toList() method
        streamOfString = Stream.of("code", "logic",
                "program", "review", "skill");
        List<String> listOfStream = streamOfString.collect(Collectors.toList());
        System.out.println("Java 8 Stream to List, 1st example : " + listOfStream);

        // Java 8 Stream to ArrayList using Collectors.toCollection method
        streamOfString = Stream.of("one", "two",
                "three", "four", "five");
        listOfStream = streamOfString.collect(Collectors.toCollection(ArrayList::new));
        System.out.println("Java 8 Stream to List, 2nd Way : " + listOfStream);

        // 3rd way to convert Stream to List in Java 8
        streamOfString = Stream.of("abc", "cde",
                "efg", "jkd", "res");
        ArrayList<String> list = new ArrayList<>();
        streamOfString.forEach(list::add);
        System.out.println("Java 8 Stream to List, 3rd Way : " + list);

        // 4th way to convert Parallel Stream to List
        streamOfString = Stream.of("one", "two",
                "three", "four", "five");
        ArrayList<String> myList = new ArrayList<>();
        streamOfString.parallel().forEachOrdered(myList::add);
        System.out.println("Java 8 Stream to List, 4th Way : " + myList);
        
        // 5th way of creating List from Stream in Java
        // but unfortunately this creates array of Objects
        // as opposed to array of String
        Stream<String> streamOfNames = Stream.of("James", "Jarry", "Jasmine", "Janeth");
        Object[] arrayOfString = streamOfNames.toArray();
        List<Object> listOfNames = Arrays.asList(arrayOfString);
        System.out.println("5th example of Stream to List in Java 8 : " + listOfNames);
        

        // can we convert the above method to String[] instead of 
        // Object[], yes by using overloaded version of toArray()
        // as shown below :
        Stream<String> streamOfShapes = Stream.of("Rectangle", "Square", "Circle", "Oval");
        String[] arrayOfShapes = streamOfShapes.toArray(String[]::new);
        List<String> listOfShapes = Arrays.asList(arrayOfShapes);
        System.out.println("modified version of last example : " + listOfShapes);

    }

}


Output :
Java 8 Stream to List, 1st example : [code, logic, program, review, skill]
Java 8 Stream to List, 2nd Way : [one, two, three, four, five]
Java 8 Stream to List, 3rd Way : [abc, cde, efg, jkd, res]
Java 8 Stream to List, 4th Way : [one, two, three, four, five]
5th example of Stream to List in Java 8 : [James, Jarry, Jasmine, Janeth]
modified version of last example : [Rectangle, Square, Circle, Oval]


That's all about how to convert Stream to List in Java 8. You have seen there are several ways to perform the conversion but I would suggest you stick with standard approach i.e. by using Stream.collect(Collectors.toList()) method.

If you like this Java 8 tutorial and hungry for more, check out following Java 8 tutorials about lambda expression, Stream API, default methods and Date Time API :
  • Java 8 - 20 Date and Time Examples for beginners (see tutorial)
  • 5 FREE Java 8 tutorials and Books (resources)
  • How to Read File in Java 8 in one line? (example)
  • Simple Java 8 Comparator Example (example)
  • Top 10 tutorials to Learn Java 8 (tutorial)
  • How to use Map function in Java 8 (example)
  • Thinking of Java 8 Certification? (read more)
  • How to read/write RandomAccessFile in Java? (solution)
  • How to use Lambda Expression in Place of Anonymous class (solution)
  • 10 Examples of Stream API in Java (examples)
  • How to filter Collection in Java 8 using Predicates? (solution)
  • How to use Default method in Java 8. (see here)
  • 10 Java 7 Feature to revisit before you starts with Java 8 (read more)


Read more: http://javarevisited.blogspot.com/2015/03/5-ways-to-convert-java-8-stream-to-list.html#ixzz3VK5EKhug

10 difference between Java and JavaScript for Programmers

Programmers, developers and internet users  have always been confused between Java and JavaScript.  Many people still thinks that JavaScript is part of Java platform, which is not true. In truth, JavaScript has nothing to do with Java, only common thing between them is word "Java", much like in Car and Carpet, or Grape and Grapefruit. JavaScript is a client side scripting language for HTML, developed by Netscape, Inc, while Java is a programming language, developed by Sun Microsystems. James Gosling is Inventor of Java, popularly known as father of Java. While in today's world calling JavaScript just a client side scripting language would not be good, as its now been used in servers also using node.js and people are doing object oriented development in JavaScript, but that was what it was originally developed. There are several difference between Java and JavaScript, from how they are written, compiled and executed. Even capability of Java and JavaScript vary significantly. Java is full feature Object oriented programming language, used in almost everywhere, starting from programming credit card to server side coding. Android uses Java as programming language for creating Android apps, Swing is a Java API used to create desktop applications and Java EE is a Java platform for developing web and enterprise applications. On the other hand JavaScript is primarily used to bring interactivity into web pages, though there are other alternatives like Flash, JavaScript is the most popular one and regaining lots of ground lost earlier with introduction of powerful and easy to use libraries like jQuery and jQuery UI. You can use JavaScript to validate user input, create animation and cool effects in HTML page and can do lot of interactive stuff e.g. reacting on button click, mouse movement, image click etc. In this article, I will share some key differences between Java and JavaScript, mostly from a programmers perspective.


Difference between Java vs JavaScript

Here is my list of key differences between JavaScript and Java as programming languages. I have worked both on them, mainly used Java for all Server Side development, Android and JavaScript for writing client side scripts to do validation, interactivity, animation and ajax calls.
Difference between Java and JavaScript

1) Execution Environment

First difference between Java and JavaScript is that Java is compiled + interpreted language, Java code is fist compiled into class files containing byte code and than executed by JVM, on the other hand JavaScript code is directly executed by browser. One more difference which comes form this fact is that, Java is run inside JVM and needs JDK or JRE for running, on there other hand JavaScript runs inside browser and almost every modern browser supports JavaScript.



2) Static vs Dynamic Typed language

Another key difference between JavaScript and Java is that, JavaScript is a dynamic typed language, while Java is a statically typed language. Which means, variables are declared with type at compile time, and can only accept values permitted for that type, other hand variables are declared using vary keyword in JavaScript, and can accept different kinds of value e.g. Stringnumeric and boolean etc. When one variable or value is compared to other using == operator, JavaScript performs type coercion. Though it also provides === operator to perform strict equality check, which checks for type as well. See here for more differences between == and == operator in JavaScript.



3) Support of Closures

JavaScript supports closures, in form of anonymous function. In simple words, you can pass a function as an argument to another function. Java doesn't treat method as first class citizen and only way to simulate closure is by using anonymous class. By the  way Java 8 has brought real closure support in Java in form of lambda expression and this has made things much easier. It's very easy to write expressive code without much clutter in Java 8.



4) OOP

Java is an Object Oriented Programming language, and though JavaScript also supports class and object, it's more like an object oriented  scripting language. It's much easier to structure code of large enterprise application in Java then JavaScript. Java provides packages to group related class together, provides much better deployment control using JAR, WAR and EAR as well.



5) Right Once Run Anywhere

Java uses byte code to achieve platform independence, JavaScript directly runs on browser, but code written in JavaScript is subject to browser compatibility issue i.e. certain code which work in Mozilla Firefox, may not work in Internet Explorer 7 or 8. This is because of browse based implementation of JavaScript. This was really bad until jQuery comes. Its a JavaScript library which helps to free web developers from this browser compatibility issues. This is why I prefer to write code using jQuery rather than using plain old JavaScript code, even if its as simple as calling getElementById() or getElementByName() methods to retrieve DOM elements.



7) Block vs Function based Scoping

Java mainly uses block based scoping i.e. a variable goes out of scope as soon as control comes out of the block, unless until its not a instance or class variable. On the other hand JavaScript mainly uses function based scoping, a variable is accessible in the function they are declared. If you have a global variable and local variable with same name, local will take precedence in JavaScript.



8) Constructors

Java has concept of constructors, which has some special properties e.g. constructor chaining and ensuring that super class constructor runs before sub class, on the other hand JavaScript constructors are just another function. There is no special rules for constructors in JavaScript e.g. they cannot have return type or their name must be same as class.



9) NullPointerException

JavaScript is much more forgiving than Java, you don't have NullPointerException in JavaScript, your variable can accept different kinds of data because of JavaScript is dynamically typed language.



10) Applicability

Last but not the least, JavaScript has it's own space, sitting cozy along with HTML and CSS in Web development, while Java is everywhere. Though both has good number of open source libraries to kick start development, but jQuery has certainly brings JavaScript on fore front.


That's all on difference between Java and JavaScript language. As I said, they are totally different language, one is a general purpose programming language, while other is scripting language for HTML. Though you can do lot of fancy stuffs using JavaScript, you still don't have features like multithreading, as compared to Java. By the way JavaScript was originally named as Livescrpit, may be due to the fact that it makes your HTML pages live, and programming world would certainly be free of this confusion, had Netscape hadn't renamed LiveScript as JavaScript.

Read more: http://javarevisited.blogspot.com/2015/03/10-difference-between-java-and-javascript-programming.html#ixzz3VK4AAW1e

Sunday, March 1, 2015

Nested Loops


We have seen the advantages of using various methods of iteration, or looping.
Now let's take a look at what happens when we combine looping procedures. 
     The placing of one loop inside the body of another loop is called nesting.  When you "nest" two loops, the outer loop takes control of the number of complete repetitions of the inner loop.  While all types of loops may be nested, the most commonly nested loops arefor loops.

nested loops
    
Let's look at an example of nested loops at work.
We have all seen web page counters that resemble the one shown below ( well, OK, maybe not quite this spastic!!).  Your car's odometer works in a similar manner.
This counter (if it worked properly) and your car's odometer are little more than seven or eight nested for loops, each going from 0 to 9.  The far-right number iterates the fastest, visibly moving from 0 to 9 as you drive your car or increasing by one as people visit a web site.  A for loop which imitates the movement of the far-right number is shown below:
for(num1 = 0; num1 <= 9; num1++)
{
      cout << num1 << endl;
}
     The far-right number, however, is not the only number that is moving.  All of the other numbers are moving also, but at a much slower pace.  For every 10 numbers that move in the column on the right, the adjacent column is incremented by one.  The two nested loops shown below may be used to imitate the movement of the two far-right numbers of a web counter or an odometer:
The number of digits in the web page counter or the odometer determine the number of nested loops needed to imitate the process.
     
When working with nested loops, the outer loop changes only after the inner loop is completely finished (or is interrupted.).
Let's take a look at a trace of two nested loops.  In order to keep the trace manageable, the number of iterations have been shortened.
for(num2 = 0; num2 <= 3;  num2++)
{
      for(num1 = 0; num1 <= 2; num1++)
      {
            cout<< num2<< "   " << num1<< endl;
      }
}
       
MemoryScreen
int num2 int num1
00
1
2
3  end loop
10
1
2
3  end loop
20
1
2
3  end loop
30
1
2
3  end loop
4  end loop
    Remember, in the memory, for loops will register a value one beyond (or the step beyond) the requested ending value in order to disengage the loop.
0   0
0   1
0   2
1   0
1   1
1   2
2   0
2   1
2   2
3   0
3   1
3   2

Rectangle Example:

Write a code fragment that prints a length by height rectangle of *'s. For example, if length is 20 and height is 10, it should print:


********************
********************
********************
********************
********************
********************
********************
********************
********************
********************

Triangle Example:

Write a code fragment that prints a length by length right triangle of *'s. For example, if length is 8, it should print:


*
**
***
****
*****
******
*******
********

Diamond Example:

Write a code fragment that prints a diamond of *'s that is n wide at its widest. For example, if n is 10, it should print:


*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
* * * * * * * * *
* * * * * * * * * *
* * * * * * * * *
* * * * * * *
* * * * * * * *
* * * * * *
* * *
* * * * * * * * * * *
*

Solutions

Rectangle Example: Write a code fragment that prints a length by height rectangle of *'s.










Triangle Example: Write a code fragment that prints a length by length right triangle of *'s.





Diamond Example: Write a code fragment that prints a diamond of *'s that is n wide at its widest.






System.out.println();
}

// print the lower pyramid
for (int row = n - 1; row > 0; row--) {

System.out.print(" ");
 for (int numStars = 0; numStars < row; numStars++)


OAuth authorization server