NodeComparator.java
1/*******************************************************************************
2 * Copyright (c) 2009, 2010 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 * Collection of comparators to compare {@link ICoverageNode} objects by
24 * different criteria.
25 *
26 * @see CounterComparator#on(ICoverageNode.CounterEntity)
27 * @author Marc R. Hoffmann
28 * @version 0.4.1.20101007204400
29 */
30public class NodeComparator implements Comparator<ICoverageNode> {
31
32 private final Comparator<ICounter> counterComparator;
33
34 private final CounterEntity entity;
35
36 NodeComparator(final Comparator<ICounter> counterComparator,
37 final CounterEntity entity) {
38 this.counterComparator = counterComparator;
39 this.entity = entity;
40 }
41
42 /**
43 * Creates a new composite comparator with a second search criterion.
44 *
45 * @param second
46 * second criterion comparator
47 *
48 * @return composite comparator
49 */
50 public NodeComparator second(final Comparator<ICoverageNode> second) {
51 final Comparator<ICoverageNode> first = this;
52 return new NodeComparator(null, null) {
53 @Override
54 public int compare(final ICoverageNode o1, final ICoverageNode o2) {
55 final int result = first.compare(o1, o2);
56 return result == 0 ? second.compare(o1, o2) : result;
57 }
58 };
59 }
60
61 /**
62 * Returns a sorted copy of the given collection of {@link ICoverageNode}
63 * elements.
64 *
65 * @param <T>
66 * actual type of the elements
67 * @param summaries
68 * collection to create a copy of
69 * @return sorted copy
70 */
71 public <T extends ICoverageNode> List<T> sort(final Collection<T> summaries) {
72 final List<T> result = new ArrayList<T>(summaries);
73 Collections.sort(result, this);
74 return result;
75 }
76
77 public int compare(final ICoverageNode n1, final ICoverageNode n2) {
78 final ICounter c1 = n1.getCounter(entity);
79 final ICounter c2 = n2.getCounter(entity);
80 return counterComparator.compare(c1, c2);
81 }
82
83}