DestutterStream.java

Download DestutterStream.java

 1: import java.util.*;
 2: import java.util.stream.Collectors;
 3: 
 4: /** Destuddering a list means to remove adjacent duplicates;
 5: *  for example, [1, 4, 2, 2, 3, 3, 5, 4] ==> [1, 4, 2, 3, 5, 4].
 6: *  (Uses include removing extra spaces between words in a document,
 7: *  removing duplicates from a sorted list (producing a "set"), and others)
 8: *  In this case, the list is the command-line arguments (Strings).
 9: *  For fun, try this: java DestutterStream "" foo
10: *
11: *  In this version, we destudder a list using the new Java 8 Streams.
12: *
13: *  @author Wayne Pollock, Tampa Florida USA
14: */
15: 
16: public class DestutterStream {
17:    public static void main ( String [] args ) {
18:       // Local variables can be used in a Lambda (or local class) only
19:       // if they are final.  Thus, "previous" is a final variable to an
20:       // array of one string (and arrays are mutable).  Tricky!
21:       final String[] previous = { null };
22: 
23:       String result = Arrays.stream( args )
24:          .filter( arg -> { boolean isDifferent = ! arg.equals(previous[0]);
25:             previous[0] = arg;
26:             return isDifferent;
27:          })
28:          .collect( Collectors.joining(", ") );
29:       System.out.println( result );
30:   }
31: }