I have a list
l = ["a","z","c","c","a","e","e"]
I need to generate a set of list as below in java
l1=["a"]
l2=["z"]
l3=["c","c"]
l4=["a"]
l5=["e","e"]
below is my code so far
package test
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class test {
public static void main(String[] args) {
List<String> l =new ArrayList<>();
List<List> ll =new ArrayList<>();
List<String> nl;
l.add("a");
l.add("z");
l.add("c");
l.add("c");
l.add("a");
l.add("a");
l.add("e");
String prev="";
nl = new ArrayList<>();
for (String x : l){
if(prev.equals(x))
{
nl.add(x);
}
else {
if(!nl.isEmpty()) {
ll.add(nl);
}
else{
List<String> nl1 = new ArrayList<>();
nl1.add(x);
ll.add(nl1);
}
}
prev=x;
}
System.out.println(ll);
}
}
output
[[a], [z], [c], [c, a], [c, a]]
expected
[[a], [z], [c,c], [a,a], [e]]
CodePudding user response:
With some little modifications to your code the below snippet should give you the disired result:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Example {
public static void main(String[] args) {
List<String> values = Arrays.asList("a","z","c","c","a","e","e");
List<List<String>> result = new ArrayList<>();
String previous = null;
List<String> subList = new ArrayList<>();
for (String value : values) {
if (previous == null || value.equals(previous)) {
subList.add(value);
} else {
result.add(subList);
subList = new ArrayList<>();
subList.add(value);
}
previous = value;
}
if (!subList.isEmpty()) {
result.add(subList);
}
System.out.println(result);
}
}
Output:
[[a], [z], [c, c], [a], [e, e]]
Another approach using streams and AtomicReference:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
public class Example {
public static void main(String[] args) {
List<String> input = Arrays.asList("a", "z", "c", "c", "a", "e", "e");
AtomicReference<String> ar = new AtomicReference<>(input.get(0));
AtomicInteger ai = new AtomicInteger();
List<List<String>> result = new ArrayList<>(
input.stream().collect(
Collectors.groupingBy(str -> str.equals(ar.getAndSet(str)) ? ai.get() : ai.incrementAndGet()))
.values());
System.out.println(result);
}
}