Java tutorial
//package com.java2s; import java.util.List; public class Main { /** Collapse consecutive duplicated tokens */ public static String collapse(String x) { return collapse(x.split(" ")); } /** Collapse consecutive duplicated tokens */ public static String collapse(String[] x) { StringBuilder sb = new StringBuilder(); String lastToken = ""; for (String token : x) { if (!lastToken.equals(token)) { sb.append(token).append(" "); lastToken = token; } } return sb.toString().trim(); } /** Collapse consecutive duplicated tokens */ public static String collapse(List<String> x) { StringBuilder sb = new StringBuilder(); String lastToken = ""; for (String token : x) { if (!lastToken.equals(token)) { sb.append(token).append(" "); lastToken = token; } } return sb.toString().trim(); } }