Streams

I tried to use lambdas to swap elements in the char[] array. Does this mean that I am trying to change the stream while it is streaming ? This code is from http://www.cs.uofs.edu/~mccloske/courses/cmps144/invariants_lec.html but this question is unrelated to those concepts.

If that is a problem then a new stream will do. How should this be done ? I am not looking for a Comparator. I would like to work with this code as it is without using any API but lambdas.

I am printing using lambdas in this code now.

public class DutchNationalFlag {

    private static final int N = 10;

    private static char[] flags = new char[]{'R','B','B','R','R','B','B','R','R','B'};

    public static void main( String... argv){

        new String(flags).chars().mapToObj(i -> (char)i).forEach(System.out::println);

        int m = 0,  k = 0;
        while (m != N)  {
            if (flags[m] == 'B') { }
            else {
                swap(flags,k,m); 
                k = k+1;
            }
            m = m+1;
        } 
        new String(flags).chars().mapToObj(i -> (char)i).forEach(System.out::println);
    }

    private static void swap(char[] flags, int k, int m) {

        char temp = flags[k];
        flags[k] = flags[m];
        flags[m] =  temp;

    }

}

Possible Solution 1:

This doesn’t do exactly what the original code does. It doesn’t swap and doesn’t advance k which is the boundary between ‘B’ and ‘R’.But it produces the result.

    Stream<Character> stream1 = 
    IntStream.range(0, flags.length).mapToObj(i -> (char)flags[i]);

    Stream<Character> stream2 = 
    IntStream.range(0, flags.length).mapToObj(i -> (char)flags[i]);


    Stream.concat(stream2.filter(x-> (x == 'B')), stream1.filter( y->(y == 'R')  )).forEach(System.out::println);

Conway’s Game of Life

This is just a simple demonstration of lambdas to implement the Cell but the code may not be complete.

package com.game.test;

import java.util.ArrayList;
import java.util.List;

import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JMock;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.runner.RunWith;

import com.game.conway.Cell;

@RunWith(JMock.class)

public class Game {

    Mockery context = new JUnit4Mockery();
    
    @SuppressWarnings("deprecation")
	@Test 
    public void mocksurvive() {
        // set up
    	context = new Mockery() {  
    		  {  
    		    setImposteriser(ClassImposteriser.INSTANCE);  
    		  }  
    		};
    	Cell cell = context.mock(Cell.class);
    	final List<Cell> cells = new ArrayList<Cell>();
		cells.add(new Cell(1,1));
		cells.add(new Cell(8,2));
		cells.add(new Cell(2,2));
		

        
        // expectations
        context.checking(new Expectations() {
             {
                 oneOf(cell).setX(1);
                 oneOf(cell).setY(1);
                 oneOf(cell).survive(cells);
                 will(returnValue(false));
             }
         });
    	cell.setX(1);
    	cell.setY(1);
         final boolean result = cell.survive(cells);

    }
}


package com.game.conway;

import java.util.List;

public class Cell implements Comparable<Cell>{
	
	public Cell(int x, int y) {
		this.x = x;
		this.y = y;
	}

	int x,y;

	public Object getX() {
		return x;
	}

	public Object getY() {
		return y;
	}

	public boolean neighbour(Cell neighbour) {
		return Math.abs(x - neighbour.x) <= 1 && 
			   Math.abs(y - neighbour.y) <= 1 &&
			   !(this.compareTo(neighbour) == 0);
	}

	public long countNeighbours(List<Cell> cells) {
		return cells.stream().filter( c -> neighbour(c)).count();
	}

	public boolean survive(List<Cell> cells) {
		long count = countNeighbours(cells);
		if(cells.stream().anyMatch( c -> (this.compareTo(c) == 0) )){
			return count == 2 || count == 3;
		}
		
		return count == 3;
	}


	@Override
	public int compareTo(Cell o) {
		if( x == o.x && y == o.y)
			return 0;
		else
			return -1;
	}
	
    
}

Succinctness of Lambdas

I think this is impressive. Compare it with the earlier way of iterating over the data. I am streaming a list of java.lang.management.GarbageCollectorMXBean‘s, accessing some data from each and creating an ArrayList of GCType objects in one line of code.

public class GarbageCollectionProbe implements Probe{
	
	Logger l = Logger.getLogger("collection.gc");

	public  List<GCType> getMemoryPool() {
		
		connectJMXRemote(9010);
 	
			List<GCType> pools =
					ManagementFactory.getGarbageCollectorMXBeans().stream().map(p-> new GCType(p.getName(),
							                                                                   p.getCollectionCount(),
							                                                                   p.getCollectionTime()))
					.collect(Collectors.toCollection(() -> new ArrayList<GCType>()));
			pools.stream().forEach(p-> l.debug(p));
			return pools;
	}	

}

Optional and Lambda

This is a piece of code that I converted using Lambdas. It is using JMX but that is irrevelant.

I wanted to use this method initially. This is the JDK source.

    /**
     * Returns an {@code Optional} describing the specified value, if non-null,
     * otherwise returns an empty {@code Optional}.
     *
     * @param <T> the class of the value
     * @param value the possibly-null value to describe
     * @return an {@code Optional} with a present value if the specified value
     * is non-null, otherwise an empty {@code Optional}
     */
    public static <T> Optional<T> ofNullable(T value) {
        return value == null ? empty() : of(value);
    }

But once I used Lambda code I realized the API returns Optional<MemoryPoolMXBean>


	   Optional<MemoryPoolMXBean> mpx = Optional.empty();


//			   for (MemoryPoolMXBean pool : memoryBeans) {
//		       		l.debug(pool.getName());
//		               if (pool.getName().equals(METASPACE)) {
//		            	   mpx =  Optional.ofNullable(pool);
//		               }
//		       }
			   
			   mpx =
			   memoryBeans
			    .stream()
			    .filter(p ->
			        {
			       	l.debug(p.getName());
			        return p.getName().equals(METASPACE);
			        })
			        .findFirst();

I don’t want to delve too deep into this as it doesn’t break the code that calls this.