Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.util.Collection;

import java.util.function.Function;

public class Main {
    public static <T, K> T copyTree(T node, Function<T, K> keyMapper, Function<T, Collection<T>> childMapper,
            Function<T, T> cloneMapper, Collection<K> toCopy) {
        if (toCopy == null)
            return null;

        T copy = null;

        Collection<T> children = childMapper.apply(node);
        if (children != null && children.size() > 0) {
            for (T child : children) {
                T childCopy = copyTree(child, keyMapper, childMapper, cloneMapper, toCopy);
                if (childCopy != null) {
                    if (copy == null)
                        copy = cloneMapper.apply(node);
                    childMapper.apply(copy).add(childCopy);
                }
            }
        }

        if (copy == null && toCopy.contains(keyMapper.apply(node)))
            copy = cloneMapper.apply(node);

        return copy;
    }
}