NodeComparator.java revision 456cb13baa8f60eef812864ed5bbe3c5f858cdbb
1/*******************************************************************************
2 * Copyright (c) 2009, 2011 Mountainminds GmbH & Co. KG and Contributors
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors:
9 *    Marc R. Hoffmann - initial API and implementation
10 *
11 *******************************************************************************/
12package org.jacoco.core.analysis;
13
14import java.util.ArrayList;
15import java.util.Collection;
16import java.util.Collections;
17import java.util.Comparator;
18import java.util.List;
19
20import org.jacoco.core.analysis.ICoverageNode.CounterEntity;
21
22/**
23 * Comparator to compare {@link ICoverageNode} objects by different counter
24 * criteria.
25 *
26 * @see CounterComparator#on(ICoverageNode.CounterEntity)
27 */
28public class NodeComparator implements Comparator<ICoverageNode> {
29
30	private final Comparator<ICounter> counterComparator;
31
32	private final CounterEntity entity;
33
34	NodeComparator(final Comparator<ICounter> counterComparator,
35			final CounterEntity entity) {
36		this.counterComparator = counterComparator;
37		this.entity = entity;
38	}
39
40	/**
41	 * Creates a new composite comparator with a second search criterion.
42	 *
43	 * @param second
44	 *            second criterion comparator
45	 *
46	 * @return composite comparator
47	 */
48	public NodeComparator second(final Comparator<ICoverageNode> second) {
49		final Comparator<ICoverageNode> first = this;
50		return new NodeComparator(null, null) {
51			@Override
52			public int compare(final ICoverageNode o1, final ICoverageNode o2) {
53				final int result = first.compare(o1, o2);
54				return result == 0 ? second.compare(o1, o2) : result;
55			}
56		};
57	}
58
59	/**
60	 * Returns a sorted copy of the given collection of {@link ICoverageNode}
61	 * elements.
62	 *
63	 * @param <T>
64	 *            actual type of the elements
65	 * @param summaries
66	 *            collection to create a copy of
67	 * @return sorted copy
68	 */
69	public <T extends ICoverageNode> List<T> sort(final Collection<T> summaries) {
70		final List<T> result = new ArrayList<T>(summaries);
71		Collections.sort(result, this);
72		return result;
73	}
74
75	public int compare(final ICoverageNode n1, final ICoverageNode n2) {
76		final ICounter c1 = n1.getCounter(entity);
77		final ICounter c2 = n2.getCounter(entity);
78		return counterComparator.compare(c1, c2);
79	}
80
81}
82