关于java:获取数组列表中元素的两两组合

45次阅读

共计 765 个字符,预计需要花费 2 分钟才能阅读完成。

创立两两组合实体类

@Data
@NoArgsConstructor
@AllArgsConstructor
public class MaterialRelevance {

    /**
     * 编码 1
     */
    private String code1;

    /**
     * 编码 2
     */
    private String code2;
}

获取两两组合

    /**
     * 获取一个数组中两两组合
     *
     * @param list
     * @return
     */
    public List<MaterialRelevance> combineTwoElement(List<String> list) {List<MaterialRelevance> resultList = Lists.newArrayListWithExpectedSize(list.size() * list.size() / 2);
        if (CollectionUtils.isEmpty(list)) {return null;}
        if (list.size() >= 2) {for (int j = 0; j < list.size(); j++) {resultList.addAll(ll(list.subList(j, list.size())));
            }
        }
        return resultList;
    }

    private List<MaterialRelevance> ll(List<String> list) {List<MaterialRelevance> resultList = Lists.newArrayListWithExpectedSize(list.size() * list.size() / 2);
        for (int j = 1; j < list.size(); j++) {resultList.add(new MaterialRelevance(list.get(0), list.get(j)));
        }
        return resultList;
    }

正文完
 0