Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

forming a specific list with Java 8 streams

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
}
like image 308
Wassim Makni Avatar asked Nov 22 '18 11:11

Wassim Makni


2 Answers

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());
like image 65
Naman Avatar answered Oct 20 '22 12:10

Naman


Using JDK 9, you can do:

IntStream.iterate(0, i -> i < source.size(), i -> i + 4)
         .mapToObj(x -> new SearchCriteria(source.get(x), source.get(x + 1), source.get(x + 2)))
         .collect(toList());
like image 39
Ousmane D. Avatar answered Oct 20 '22 12:10

Ousmane D.