More lambdas, less boilerplate.

This commit is contained in:
Gary Gregory 2019-09-12 20:42:35 -04:00
parent 15d9a6b052
commit 3ea8244287
13 changed files with 97 additions and 161 deletions

View File

@ -7758,12 +7758,7 @@ public class ArrayUtils {
* @since 3.4
*/
public static <T extends Comparable<? super T>> boolean isSorted(final T[] array) {
return isSorted(array, new Comparator<T>() {
@Override
public int compare(final T o1, final T o2) {
return o1.compareTo(o2);
}
});
return isSorted(array, (o1, o2) -> o1.compareTo(o2));
}

View File

@ -1376,82 +1376,73 @@ public class ClassUtils {
* @since 3.2
*/
public static Iterable<Class<?>> hierarchy(final Class<?> type, final Interfaces interfacesBehavior) {
final Iterable<Class<?>> classes = new Iterable<Class<?>>() {
final Iterable<Class<?>> classes = () -> {
final MutableObject<Class<?>> next = new MutableObject<>(type);
return new Iterator<Class<?>>() {
@Override
public Iterator<Class<?>> iterator() {
final MutableObject<Class<?>> next = new MutableObject<>(type);
return new Iterator<Class<?>>() {
@Override
public boolean hasNext() {
return next.getValue() != null;
}
@Override
public boolean hasNext() {
return next.getValue() != null;
}
@Override
public Class<?> next() {
final Class<?> result = next.getValue();
next.setValue(result.getSuperclass());
return result;
}
@Override
public Class<?> next() {
final Class<?> result = next.getValue();
next.setValue(result.getSuperclass());
return result;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
};
if (interfacesBehavior != Interfaces.INCLUDE) {
return classes;
}
return new Iterable<Class<?>>() {
return () -> {
final Set<Class<?>> seenInterfaces = new HashSet<>();
final Iterator<Class<?>> wrapped = classes.iterator();
@Override
public Iterator<Class<?>> iterator() {
final Set<Class<?>> seenInterfaces = new HashSet<>();
final Iterator<Class<?>> wrapped = classes.iterator();
return new Iterator<Class<?>>() {
Iterator<Class<?>> interfaces = Collections.<Class<?>>emptySet().iterator();
return new Iterator<Class<?>>() {
Iterator<Class<?>> interfaces = Collections.<Class<?>>emptySet().iterator();
@Override
public boolean hasNext() {
return interfaces.hasNext() || wrapped.hasNext();
}
@Override
public boolean hasNext() {
return interfaces.hasNext() || wrapped.hasNext();
@Override
public Class<?> next() {
if (interfaces.hasNext()) {
final Class<?> nextInterface = interfaces.next();
seenInterfaces.add(nextInterface);
return nextInterface;
}
final Class<?> nextSuperclass = wrapped.next();
final Set<Class<?>> currentInterfaces = new LinkedHashSet<>();
walkInterfaces(currentInterfaces, nextSuperclass);
interfaces = currentInterfaces.iterator();
return nextSuperclass;
}
@Override
public Class<?> next() {
if (interfaces.hasNext()) {
final Class<?> nextInterface = interfaces.next();
seenInterfaces.add(nextInterface);
return nextInterface;
private void walkInterfaces(final Set<Class<?>> addTo, final Class<?> c) {
for (final Class<?> iface : c.getInterfaces()) {
if (!seenInterfaces.contains(iface)) {
addTo.add(iface);
}
final Class<?> nextSuperclass = wrapped.next();
final Set<Class<?>> currentInterfaces = new LinkedHashSet<>();
walkInterfaces(currentInterfaces, nextSuperclass);
interfaces = currentInterfaces.iterator();
return nextSuperclass;
walkInterfaces(addTo, iface);
}
}
private void walkInterfaces(final Set<Class<?>> addTo, final Class<?> c) {
for (final Class<?> iface : c.getInterfaces()) {
if (!seenInterfaces.contains(iface)) {
addTo.add(iface);
}
walkInterfaces(addTo, iface);
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
};
};
}

View File

@ -115,13 +115,7 @@ public class Memoizer<I, O> implements Computable<I, O> {
while (true) {
Future<O> future = cache.get(arg);
if (future == null) {
final Callable<O> eval = new Callable<O>() {
@Override
public O call() throws InterruptedException {
return computable.compute(arg);
}
};
final Callable<O> eval = () -> computable.compute(arg);
final FutureTask<O> futureTask = new FutureTask<>(eval);
future = cache.putIfAbsent(arg, futureTask);
if (future == null) {

View File

@ -417,12 +417,7 @@ public class TimedSemaphore {
* @return a future object representing the task scheduled
*/
protected ScheduledFuture<?> startTimer() {
return getExecutorService().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
endOfPeriod();
}
}, getPeriod(), getPeriod(), getUnit());
return getExecutorService().scheduleAtFixedRate(() -> endOfPeriod(), getPeriod(), getPeriod(), getUnit());
}
/**

View File

@ -1715,12 +1715,7 @@ public class TypeUtils {
* @since 3.2
*/
public static <T> Typed<T> wrap(final Type type) {
return new Typed<T>() {
@Override
public Type getType() {
return type;
}
};
return () -> type;
}
/**

View File

@ -94,12 +94,7 @@ public class FastDateParser implements DateParser, Serializable {
// comparator used to sort regex alternatives
// alternatives should be ordered longer first, and shorter last. ('february' before 'feb')
// all entries must be lowercase by locale.
private static final Comparator<String> LONGER_FIRST_LOWERCASE = new Comparator<String>() {
@Override
public int compare(final String left, final String right) {
return right.compareTo(left);
}
};
private static final Comparator<String> LONGER_FIRST_LOWERCASE = (left, right) -> right.compareTo(left);
/**
* <p>Constructs a new FastDateParser.</p>

View File

@ -35,7 +35,6 @@ import java.lang.annotation.Target;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.time.Duration;
import java.util.Collection;
@ -465,21 +464,17 @@ public class AnnotationUtilsTest {
final Test real = getClass().getDeclaredMethod(
"testGeneratedAnnotationEquivalentToRealAnnotation").getAnnotation(Test.class);
final InvocationHandler generatedTestInvocationHandler = new InvocationHandler() {
@Override
public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
if ("equals".equals(method.getName()) && method.getParameterTypes().length == 1) {
return Boolean.valueOf(proxy == args[0]);
}
if ("hashCode".equals(method.getName()) && method.getParameterTypes().length == 0) {
return Integer.valueOf(System.identityHashCode(proxy));
}
if ("toString".equals(method.getName()) && method.getParameterTypes().length == 0) {
return "Test proxy";
}
return method.invoke(real, args);
final InvocationHandler generatedTestInvocationHandler = (proxy, method, args) -> {
if ("equals".equals(method.getName()) && method.getParameterTypes().length == 1) {
return Boolean.valueOf(proxy == args[0]);
}
if ("hashCode".equals(method.getName()) && method.getParameterTypes().length == 0) {
return Integer.valueOf(System.identityHashCode(proxy));
}
if ("toString".equals(method.getName()) && method.getParameterTypes().length == 0) {
return "Test proxy";
}
return method.invoke(real, args);
};
final Test generated = (Test) Proxy.newProxyInstance(Thread.currentThread()

View File

@ -4394,12 +4394,7 @@ public class ArrayUtilsTest {
@Test
public void testIsSortedComparator() {
final Comparator<Integer> c = new Comparator<Integer>() {
@Override
public int compare(final Integer o1, final Integer o2) {
return o2.compareTo(o1);
}
};
final Comparator<Integer> c = (o1, o2) -> o2.compareTo(o1);
Integer[] array = null;
assertTrue(ArrayUtils.isSorted(array, c));

View File

@ -90,25 +90,19 @@ public class ReflectionToStringBuilderConcurrencyTest {
// Create a thread pool with two threads to cause the most contention on the underlying resource.
final ExecutorService threadPool = Executors.newFixedThreadPool(2);
// Consumes toStrings
final Callable<Integer> consumer = new Callable<Integer>() {
@Override
public Integer call() {
for (int i = 0; i < REPEAT; i++) {
final String s = ReflectionToStringBuilder.toString(holder);
assertNotNull(s);
}
return Integer.valueOf(REPEAT);
final Callable<Integer> consumer = () -> {
for (int i = 0; i < REPEAT; i++) {
final String s = ReflectionToStringBuilder.toString(holder);
assertNotNull(s);
}
return Integer.valueOf(REPEAT);
};
// Produces changes in the list
final Callable<Integer> producer = new Callable<Integer>() {
@Override
public Integer call() {
for (int i = 0; i < DATA_SIZE; i++) {
list.remove(list.get(0));
}
return Integer.valueOf(REPEAT);
final Callable<Integer> producer = () -> {
for (int i = 0; i < DATA_SIZE; i++) {
list.remove(list.get(0));
}
return Integer.valueOf(REPEAT);
};
final Collection<Callable<Integer>> tasks = new ArrayList<>();
tasks.add(consumer);

View File

@ -89,15 +89,12 @@ public class ToStringStyleConcurrencyTest {
// Create a thread pool with two threads to cause the most contention on the underlying resource.
final ExecutorService threadPool = Executors.newFixedThreadPool(2);
// Consumes toStrings
final Callable<Integer> consumer = new Callable<Integer>() {
@Override
public Integer call() {
for (int i = 0; i < REPEAT; i++) {
// Calls ToStringStyle
new ToStringBuilder(holder).append(holder.collection);
}
return Integer.valueOf(REPEAT);
final Callable<Integer> consumer = () -> {
for (int i = 0; i < REPEAT; i++) {
// Calls ToStringStyle
new ToStringBuilder(holder).append(holder.collection);
}
return Integer.valueOf(REPEAT);
};
final Collection<Callable<Integer>> tasks = new ArrayList<>();
tasks.add(consumer);

View File

@ -136,11 +136,7 @@ public class EventListenerSupportTest {
@Test
public void testSerialization() throws IOException, ClassNotFoundException, PropertyVetoException {
final EventListenerSupport<VetoableChangeListener> listenerSupport = EventListenerSupport.create(VetoableChangeListener.class);
listenerSupport.addListener(new VetoableChangeListener() {
@Override
public void vetoableChange(final PropertyChangeEvent e) {
}
listenerSupport.addListener(e -> {
});
listenerSupport.addListener(EasyMock.createNiceMock(VetoableChangeListener.class));

View File

@ -79,11 +79,8 @@ public class EventUtilsTest {
public void testAddEventListenerThrowsException() {
final ExceptionEventSource src = new ExceptionEventSource();
assertThrows(RuntimeException.class, () ->
EventUtils.addEventListener(src, PropertyChangeListener.class, new PropertyChangeListener() {
@Override
public void propertyChange(final PropertyChangeEvent e) {
// Do nothing!
}
EventUtils.addEventListener(src, PropertyChangeListener.class, e -> {
// Do nothing!
})
);
}

View File

@ -257,28 +257,25 @@ public class FastDateFormatTest {
final AtomicLongArray totalElapsed= new AtomicLongArray(2);
for (int i= 0; i<NTHREADS; ++i) {
pool.submit(new Runnable() {
@Override
public void run() {
for (int j= 0; j<NROUNDS; ++j) {
try {
final Date date= new Date();
pool.submit(() -> {
for (int j= 0; j<NROUNDS; ++j) {
try {
final Date date= new Date();
final long t0= System.currentTimeMillis();
final String formattedDate= printer.format(date);
totalElapsed.addAndGet(0, System.currentTimeMillis() - t0);
final long t0= System.currentTimeMillis();
final String formattedDate= printer.format(date);
totalElapsed.addAndGet(0, System.currentTimeMillis() - t0);
final long t1 = System.currentTimeMillis();
final Object pd= parser.parseObject(formattedDate);
totalElapsed.addAndGet(1, System.currentTimeMillis() - t1);
final long t1 = System.currentTimeMillis();
final Object pd= parser.parseObject(formattedDate);
totalElapsed.addAndGet(1, System.currentTimeMillis() - t1);
if (!date.equals(pd)) {
failures.incrementAndGet();
}
} catch (final Exception e) {
if (!date.equals(pd)) {
failures.incrementAndGet();
e.printStackTrace();
}
} catch (final Exception e) {
failures.incrementAndGet();
e.printStackTrace();
}
}
});