Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import java.util.*;

public class Main {
    /**
     * Reorder a list of elements by another list. Trying to keep absolute order of initial list in alphabetical order
     * but reorder regarding to provided relative order list.
     * E.g. initial was [1, 2, 3, 4, 5] - calling reorder with list [2, 5, 4] will generate list
     * [1, 2, 3, 5, 4]
     * @param elements - initial list
     * @param order - list describing relative order
     * @param <T> - Class of comparable object
     * @return - new reordered list
     */
    public static <T extends Comparable> List<T> mergeReorder(List<T> elements, List<T> order) {
        if (order.size() == 0) {
            return elements;
        }
        if (elements.size() == 0) {
            return order;
        }
        Set<T> merged = new LinkedHashSet<>();
        Set<T> elementsSet = new HashSet<>(elements);
        int i = 0;
        int j = 0;
        T currElement = elements.get(i);
        T currOrder = order.get(j);
        while (i < elements.size() || j < order.size()) {
            if (j >= order.size()) {
                merged.addAll(elements.subList(i, elements.size()));
                break;
            }
            currElement = i < elements.size() ? elements.get(i) : currElement;
            currOrder = j < order.size() ? order.get(j) : currOrder;
            if (currElement.compareTo(currOrder) < 0) {
                merged.add(currElement);
                i++;
            }
            if (currOrder.compareTo(currElement) < 0 || i >= elements.size()) {
                if (merged.contains(currOrder)) {
                    merged.remove(currOrder);
                }
                if (elementsSet.contains(currOrder)) {
                    merged.add(currOrder);
                }
                j++;
            }
            if (currElement.compareTo(currOrder) == 0) {
                merged.add(currElement);
                i++;
                j++;
            }
        }
        return new ArrayList<>(merged);
    }
}