How to Rewrite the Code Below Using Streams in java8

advertisements
private void enrichWithFieldList(String desc, String value, List<Data> dataList, List<Field> fieldList) {
        int index = 1;
        for(Data data : dataList){
            if(!"english".equals(data.getCode())){
                createFieldList(desc+index, data.getCode(), fieldList);
                createFieldList(value+index++, data.getValue(), fieldList);
            }
        }
    }

private void createFieldList(String fieldName, String fieldValue, List<Field> fieldList) {
        Field customField = new Field();
        customField.setName(fieldName);
        customField.setValue(fieldValue);
        fieldList.add(customField);
}

Can anybody tell me how to rewrite the above code using Java8 streams?


As far as I can tell your trying to come up with a new list of fields based on your data list. If so, probably best to create that directly from a stream rather than add to a list passed into your method.

Something like the following:

private List<Field> makeEnrichedFieldList(String desc, String value, List<Data> dataList) {
    return IntStream.range(0, dataList.size())
        .filter(i -> !dataList.get(i).getCode().equals("english"))
        .boxed ()
        .flatMap(i -> Stream.of(new Field(desc + i + 1, dataList.get(i).getCode()),
                                new Field(value + i + 1, dataList.get(i).getValue()))
        .collect(Collectors.toList());
}