用Java 8流形成特定列表

时间:2018-11-22 11:50:54

标签: java java-8 java-stream

我目前在一个Java项目中工作,我有一个字符串列表,我希望它们使用流具有特定的格式。

例如

输入:[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
}]

我没有使用流就编写了非常基本的代码:

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类

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
}

2 个答案:

答案 0 :(得分:4)

对于Java Aomine's answer 8版本,您可以使用:

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());

或者,类似于Holger的建议,您可以将IntStream的rangeClosed API用作:

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());

答案 1 :(得分:2)

使用JDK 9,您可以执行以下操作:

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());