forming a specific list with Java 8 streams

  • A+
Category:Languages

I'am currently working in a java project which I have a list of strings and I want them to have a specific format using streams .

For example

Input : [nom, contains, b, and, prenom, contains, y, and, age, >=, 1, and, age, <=, 100] Ouput:

[ {key:"nom", operation:"contains", value:"b" }, { key:"prenom", operation:"contains", value:"y" }, { key:"age", operation:">=", value: 1 }, { key:"age", operation:"<=", value: 1000 }] 

I wrote a very basic code without using streams:

List filter = [nom, contains, b, and, prenom, contains, y, and, age, >=, 1, and, age, <=, 100]     List<SearchCriteria> formedFilter = new ArrayList<>();     SearchCriteria sc = new SearchCriteria();     if(filter != null){         for(int i = 0 ;i< filter.size();i++){             if(i % 4 ==0){                 sc.setKey((String) filter.get(i));             }else if(i % 4 == 1){                 sc.setOperation((String) filter.get(i));              }else if(i % 4 ==2){                 sc.setValue(filter.get(i));                 formedFilter.add(sc);              }else{                 sc = new SearchCriteria();             }         }     } 

SearchCriteria Class

public class SearchCriteria {     private String key;     private String operation;     private Object value;      public SearchCriteria() {     }      public SearchCriteria(String key, String operation, Object value) {         this.key = key;         this.operation = operation;         this.value = value;     }     // getters and setters } 

 


For a Java 8 version of Aomine's answer you can use:

List<SearchCriteria> formedFilter = IntStream.iterate(0, i -> i + 4)             .limit(filter.size() / 4 + 1) // + 1 to consider the last group as well             .mapToObj(i -> new SearchCriteria(filter.get(i), filter.get(i + 1), filter.get(i + 2)))             .collect(Collectors.toList()); 

Alternatively, similar to a suggestion by Holger, you can use the rangeClosed API from IntStream as:

List<SearchCriteria> formedFilter2 = IntStream.rangeClosed(0, filter.size() / 4)         .map(i -> i * 4)         .mapToObj(i -> new SearchCriteria(filter.get(i), filter.get(i + 1), filter.get(i + 2)))         .collect(Collectors.toList()); 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: