Tuesday, July 21, 2015

Java 8 lambda examples II

Generate an array of random Integer values:
   private static final Random random = new Random();  
   public static Integer[] generateRandomIntArray(int size) {  
     return IntStream.range(0, size).map(i -> random.nextInt(size)).boxed()  

Reverse an array:
     IntStream.range(0, randomNumbers.length / 2)  
         .forEach(i -> swap(randomNumbers, i, randomNumbers.length - i - 1));  

Do bubble sort:
     IntStream.range(0, items.length)  
         .forEach(i -> IntStream.range(i + 1, items.length)  
             .filter(j -> items[i]> items[j])  
             .forEach(j -> swap(items, i, j)));  

Friday, July 3, 2015

Testing your main method

I wrote a lot of simple applications, mostly to just try things out, that run on text console and for user interactions use System.out.println and An issue is how to test these programs. Here is a simple way. Move your logic from your static main method to the object and parameterize the & System.out. Like from this :
 public class ShouterMain {  
   public static void main(String... args) throws Exception {  
     String id = UUID.randomUUID().toString();  
     final MulticastSocket socket = new MulticastSocket(4444);  

to this:
   public static void main(String... args) throws Exception {  
     new ShouterMain(System.out,;  

To test use ByteArray Streams:
     final List<String> firstClientLines = new ArrayList<>();  
     try (  
         PrintStream firstOut = new PrintStream(new ByteArrayOutputStream()) {  
           public void println(String str) {  
         InputStream firstIn = new ByteArrayInputStream(new byte[]{});  
     ) {  
       new ShouterMain(firstOut, firstIn).doMain();  
       Assert.assertEquals("Someone shouted: 'I am Second!'", firstClientLines.get(0));  

Thursday, July 2, 2015

MulticastSocket example

This simple example when run sends whatever entered over a multicast ip address. Also listens and prints whatever is send through others. You can launch up multiple instances and sort of chat...

Wednesday, July 1, 2015

Java 8 lambda examples

Input file :

Read a file line by line and print :
     try (BufferedReader reader = new BufferedReader(  
         new InputStreamReader(Example.class.getResourceAsStream("/input.txt")))) {  
       reader.lines().forEach(line -> System.out.println(line));  
     } catch (IOException e) {  
       throw new RuntimeException(e);  

or collect them in a list:

       List<String> lineList = reader.lines()

or sum all the numbers:

       int sum = reader.lines()
                       .mapToInt(line -> Integer.parseInt(line)).sum();  

or maybe just add only the positive values:
       int sum = reader.lines()
                       .mapToInt(line -> Integer.parseInt(line))
                       .filter(anInt -> anInt > 0).sum();