I need to write the following block of code using Java Stream. Can someone please help me out? I’m not familiar with java streams

The code below basically ignores the string “header”. I need to write the same code using java stream

List<String> dataitem1=new ArrayList<>();
dataitem1.add("header");
dataitem1.add("B");
dataitem1.add("C");
List<String> dataitem2=new ArrayList<>();
dataitem2.add("header");
dataitem2.add("B");
dataitem2.add("C");
List<List<String>> data=Arrays.asList(dataitem1,dataitem2);
String x=null;
for(int i=0;i<data.size();i++){
    for(int j=0;j<data.get(i).size();j++){
                if((i==0 && j==0) || data.get(i).get(j).equals(x)){
                    x=data.get(i).get(j);
                    continue;
                }
                System.out.println(data.get(i).get(j));
            }
}

Answer

use filter method.

list.stream()
    .flatMap(List::stream)
    .filter(Predicate.not(str -> str.equals("header")))
    .collect(Collectors.toList());

Inorder to replace the string “header” with another rather than ignoring it, you need to replace the filter statement with

.map(str -> (str.equals("header") ? "anotherstring" : str))

Leave a Reply

Your email address will not be published. Required fields are marked *