Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.util.Collection;
import java.util.Comparator;

import java.util.List;
import java.util.ListIterator;

import java.util.function.BiPredicate;

public class Main {
    public static <E> boolean addAllToSortedList(List<E> list, Collection<? extends E> itemsToAdd,
            Comparator<? super E> comparator, BiPredicate<? super E, ? super E> distincter) {
        boolean changed = false;
        for (E item : itemsToAdd) {
            if (addToSortedList(list, item, comparator, distincter)) {
                changed = true;
            }
        }
        return changed;
    }

    public static <E> boolean addToSortedList(List<E> list, E item, Comparator<? super E> comparator,
            BiPredicate<? super E, ? super E> distincter) {
        int addIndex = list.size();
        boolean foundAddIndex = false;
        ListIterator<E> iter = list.listIterator();
        while (iter.hasNext()) {
            int currIndex = iter.nextIndex();
            E currItem = iter.next();
            if (distincter != null && distincter.test(currItem, item)) {
                return false;
            }
            if (!foundAddIndex) {
                int comparison = comparator.compare(currItem, item);
                if (comparison > 0) {
                    addIndex = currIndex;
                    // if we don't have to check the remaining items for distinct we can break the loop now
                    if (distincter == null) {
                        break;
                    }
                    foundAddIndex = true;
                } else if (comparison == 0) {
                    addIndex = currIndex + 1;
                    // if we don't have to check the remaining items for distinct we can break the loop now
                    if (distincter == null) {
                        break;
                    }
                    foundAddIndex = true;
                }
            }
        }
        list.add(addIndex, item);
        return true;
    }
}