Java Code Examples for java.util.Set#clear()

The following examples show how to use java.util.Set#clear() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractGraphPathSearch.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Updates the cost of the vertex using its existing cost plus the
 * cost to traverse the specified edge. If the search is in single
 * path mode, only one path will be accrued.
 *
 * @param vertex  vertex to update
 * @param edge    edge through which vertex is reached
 * @param cost    current cost to reach the vertex from the source
 * @param replace true to indicate that any accrued edges are to be
 *                cleared; false to indicate that the edge should be
 *                added to the previously accrued edges as they yield
 *                the same cost
 */
void updateVertex(V vertex, E edge, Weight cost, boolean replace) {
    costs.put(vertex, cost);
    if (edge != null) {
        Set<E> edges = parents.get(vertex);
        if (edges == null) {
            edges = new HashSet<>();
            parents.put(vertex, edges);
        }
        if (replace) {
            edges.clear();
        }
        if (maxPaths == ALL_PATHS || edges.size() < maxPaths) {
            edges.add(edge);
        }
    }
}
 
Example 2
Source File: NamespacesTest.java    From rdf4j with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Test method for {@link org.eclipse.rdf4j.model.util.Namespaces#wrap(java.util.Set)}.
 */
@Test
public final void testWrapKeySet() throws Exception {
	Set<Namespace> testSet = new LinkedHashSet<>();
	Map<String, String> testMap = Namespaces.wrap(testSet);

	Set<String> keySet1 = testMap.keySet();
	assertNotNull(keySet1);
	assertTrue(keySet1.isEmpty());

	testSet.add(new SimpleNamespace(testPrefix1, testName1));

	Set<String> keySet2 = testMap.keySet();
	assertNotNull(keySet2);
	assertFalse(keySet2.isEmpty());
	assertEquals(1, keySet2.size());
	String nextKey = keySet2.iterator().next();
	assertEquals(testPrefix1, nextKey);

	testSet.clear();

	Set<String> keySet3 = testMap.keySet();
	assertNotNull(keySet3);
	assertTrue(keySet3.isEmpty());
}
 
Example 3
Source File: WebAcFilterTest.java    From trellis with Apache License 2.0 6 votes vote down vote up
@Test
void testFilterWrite() {
    final Set<IRI> modes = new HashSet<>();
    when(mockContext.getMethod()).thenReturn("PUT");
    when(mockWebAcService.getAuthorizedModes(any(IRI.class), any(Session.class)))
        .thenReturn(new AuthorizedModes(effectiveAcl, modes));

    final WebAcFilter filter = new WebAcFilter();
    filter.setAccessService(mockWebAcService);
    modes.add(ACL.Write);
    assertDoesNotThrow(() -> filter.filter(mockContext), "Unexpected exception after adding Write ability!");

    modes.clear();
    assertThrows(NotAuthorizedException.class, () -> filter.filter(mockContext),
            "No expception thrown when not authorized!");

    when(mockContext.getSecurityContext()).thenReturn(mockSecurityContext);
    assertThrows(ForbiddenException.class, () -> filter.filter(mockContext),
            "No exception thrown!");
}
 
Example 4
Source File: EnumSetTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * java.util.EnumSet#clear()
 */
public void test_clear() {
    Set<EnumFoo> set = EnumSet.noneOf(EnumFoo.class);
    set.add(EnumFoo.a);
    set.add(EnumFoo.b);
    assertEquals("Size should be 2", 2, set.size());

    set.clear();

    assertEquals("Size should be 0", 0, set.size());

    // test enum type with more than 64 elements
    Set<HugeEnum> hugeSet = EnumSet.allOf(HugeEnum.class);
    assertEquals(65, hugeSet.size());

    boolean result = hugeSet.contains(HugeEnum.aa);
    assertTrue(result);

    hugeSet.clear();
    assertEquals(0, hugeSet.size());
    result = hugeSet.contains(HugeEnum.aa);
    assertFalse(result);
}
 
Example 5
Source File: JpaPersistenceServiceImplClustersIntegrationTest.java    From genie with Apache License 2.0 6 votes vote down vote up
@Test
@DatabaseSetup("persistence/clusters/init.xml")
void testGetClustersByTags() {
    final Set<String> tags = Sets.newHashSet("prod");
    Page<Cluster> clusters = this.service.findClusters(null, null, tags, null, null, PAGE);
    Assertions.assertThat(clusters.getNumberOfElements()).isEqualTo(1);
    Assertions.assertThat(clusters.getContent().get(0).getId()).isEqualTo(CLUSTER_1_ID);

    tags.clear();
    tags.add("hive");
    clusters = this.service.findClusters(null, null, tags, null, null, PAGE);
    Assertions.assertThat(clusters.getNumberOfElements()).isEqualTo(2);
    Assertions.assertThat(clusters.getContent().get(0).getId()).isEqualTo(CLUSTER_2_ID);
    Assertions.assertThat(clusters.getContent().get(1).getId()).isEqualTo(CLUSTER_1_ID);

    tags.add("somethingThatWouldNeverReallyExist");
    clusters = this.service.findClusters(null, null, tags, null, null, PAGE);
    Assertions.assertThat(clusters.getContent()).isEmpty();

    tags.clear();
    clusters = this.service.findClusters(null, null, tags, null, null, PAGE);
    Assertions.assertThat(clusters.getNumberOfElements()).isEqualTo(2);
    Assertions.assertThat(clusters.getContent().get(0).getId()).isEqualTo(CLUSTER_2_ID);
    Assertions.assertThat(clusters.getContent().get(1).getId()).isEqualTo(CLUSTER_1_ID);
}
 
Example 6
Source File: Classes.java    From sis with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the interfaces which are implemented by the two given classes. The returned set
 * does not include the parent interfaces. For example if the two given objects implement the
 * {@link Collection} interface, then the returned set will contain the {@code Collection}
 * type but not the {@link Iterable} type, since it is implied by the collection type.
 *
 * @param  c1  the first class.
 * @param  c2  the second class.
 * @return the interfaces common to both classes, or an empty set if none.
 *         Callers can freely modify the returned set.
 */
public static Set<Class<?>> findCommonInterfaces(final Class<?> c1, final Class<?> c2) {
    final Set<Class<?>> interfaces = getInterfaceSet(c1);
    final Set<Class<?>> buffer     = getInterfaceSet(c2);               // To be recycled.
    if (interfaces == null || buffer == null) {
        return Collections.emptySet();
    }
    interfaces.retainAll(buffer);
    for (Iterator<Class<?>> it=interfaces.iterator(); it.hasNext();) {
        final Class<?> candidate = it.next();
        buffer.clear();     // Safe because the buffer can not be Collections.EMPTY_SET at this point.
        getInterfaceSet(candidate, buffer);
        if (interfaces.removeAll(buffer)) {
            it = interfaces.iterator();
        }
    }
    return interfaces;
}
 
Example 7
Source File: TimelineSelectionOverlay.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static void updateValues(Set<Point> values,
                                 List<ItemSelection> selectedItems,
                                 TimelineChart chart) {
    values.clear();
    for (ItemSelection sel : selectedItems) {
        XYItemSelection xySel = (XYItemSelection)sel;
        XYItem item = xySel.getItem();
        TimelineXYPainter painter = (TimelineXYPainter)chart.getPaintersModel().getPainter(item);
        ChartContext context = chart.getChartContext(item);
        long xValue = item.getXValue(xySel.getValueIndex());
        long yValue = item.getYValue(xySel.getValueIndex());
        int xPos = Utils.checkedInt(Math.ceil(context.getViewX(xValue)));
        int yPos = Utils.checkedInt(Math.ceil(painter.getItemView(yValue, item, context)));
        if (xPos >= 0 && xPos <= chart.getWidth()) values.add(new Point(xPos, yPos));
    }
}
 
Example 8
Source File: PrivacyEnforcementService.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
private Set<String> extractCcpaEnforcedBidders(List<String> bidders, BidRequest bidRequest, BidderAliases aliases) {
    final Set<String> ccpaEnforcedBidders = new HashSet<>(bidders);

    final ExtBidRequest extBidRequest = requestExt(bidRequest);
    final ExtRequestPrebid extRequestPrebid = extBidRequest != null ? extBidRequest.getPrebid() : null;
    final List<String> nosaleBidders = extRequestPrebid != null
            ? ListUtils.emptyIfNull(extRequestPrebid.getNosale())
            : Collections.emptyList();

    if (nosaleBidders.size() == 1 && nosaleBidders.contains(CATCH_ALL_BIDDERS)) {
        ccpaEnforcedBidders.clear();
    } else {
        ccpaEnforcedBidders.removeAll(nosaleBidders);
    }

    ccpaEnforcedBidders.removeIf(bidder ->
            !bidderCatalog.bidderInfoByName(aliases.resolveBidder(bidder)).isCcpaEnforced());

    return ccpaEnforcedBidders;
}
 
Example 9
Source File: ExecutionVertex.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the location preferences of the vertex's current task execution, as determined by the locations
 * of the predecessors from which it receives input data.
 * If there are more than MAX_DISTINCT_LOCATIONS_TO_CONSIDER different locations of source data, this
 * method returns {@code null} to indicate no location preference.
 *
 * @return The preferred locations based in input streams, or an empty iterable,
 *         if there is no input-based preference.
 */
public Collection<CompletableFuture<TaskManagerLocation>> getPreferredLocationsBasedOnInputs() {
	// otherwise, base the preferred locations on the input connections
	if (inputEdges == null) {
		return Collections.emptySet();
	}
	else {
		Set<CompletableFuture<TaskManagerLocation>> locations = new HashSet<>(getTotalNumberOfParallelSubtasks());
		Set<CompletableFuture<TaskManagerLocation>> inputLocations = new HashSet<>(getTotalNumberOfParallelSubtasks());

		// go over all inputs
		for (int i = 0; i < inputEdges.length; i++) {
			inputLocations.clear();
			ExecutionEdge[] sources = inputEdges[i];
			if (sources != null) {
				// go over all input sources
				for (int k = 0; k < sources.length; k++) {
					// look-up assigned slot of input source
					CompletableFuture<TaskManagerLocation> locationFuture = sources[k].getSource().getProducer().getCurrentTaskManagerLocationFuture();
					// add input location
					inputLocations.add(locationFuture);
					// inputs which have too many distinct sources are not considered
					if (inputLocations.size() > MAX_DISTINCT_LOCATIONS_TO_CONSIDER) {
						inputLocations.clear();
						break;
					}
				}
			}
			// keep the locations of the input with the least preferred locations
			if (locations.isEmpty() || // nothing assigned yet
					(!inputLocations.isEmpty() && inputLocations.size() < locations.size())) {
				// current input has fewer preferred locations
				locations.clear();
				locations.addAll(inputLocations);
			}
		}

		return locations.isEmpty() ? Collections.emptyList() : locations;
	}
}
 
Example 10
Source File: AuthoringController.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
    * Delete a topic form current topic list. But database record will be deleted only when user save whole authoring
    * page.
    */
   @RequestMapping(path = "/deleteTopic", method = RequestMethod.POST)
   public String deleteTopic(HttpServletRequest request) throws PersistenceException {

// get SessionMAP
String sessionMapID = WebUtil.readStrParam(request, ForumConstants.ATTR_SESSION_MAP_ID);
SessionMap<String, Object> sessionMap = (SessionMap<String, Object>) request.getSession()
	.getAttribute(sessionMapID);
request.setAttribute(ForumConstants.ATTR_SESSION_MAP_ID, sessionMapID);
String topicIndex = request.getParameter(ForumConstants.AUTHORING_TOPICS_INDEX);
int topicIdx = NumberUtils.stringToInt(topicIndex, -1);

if (topicIdx != -1) {
    Set topics = getTopics(sessionMap);
    List<MessageDTO> rList = new ArrayList<MessageDTO>(topics);
    MessageDTO item = rList.remove(topicIdx);
    topics.clear();
    topics.addAll(rList);
    // add to delList
    List delList = getDeletedTopicList(sessionMap);
    delList.add(item);

    SortedSet<ForumCondition> list = getForumConditionSet(sessionMap);
    Iterator<ForumCondition> conditionIter = list.iterator();

    while (conditionIter.hasNext()) {
	ForumCondition condition = conditionIter.next();
	Set<Message> topicList = condition.getTopics();
	if (topicList.contains(item.getMessage())) {
	    topicList.remove(item.getMessage());
	}
    }
}

return "jsps/authoring/message/topiclist";
   }
 
Example 11
Source File: IndexSearchServiceImpl.java    From herd with Apache License 2.0 5 votes vote down vote up
/**
 * Validates a set of search match fields. This method also trims and lowers the match fields.
 *
 * @param match the search match fields to be validated
 */
private void validateSearchMatchFields(Set<String> match)
{
    // Create a local copy of the match fields set so that we can stream it to modify the match fields set
    Set<String> localCopy = new HashSet<>(match);

    // Clear the match set
    match.clear();

    // Add to the match set field the strings both trimmed and lower cased and filter out empty and null strings
    localCopy.stream().filter(StringUtils::isNotBlank).map(String::trim).map(String::toLowerCase).forEachOrdered(match::add);

    // Validate the field names
    match.forEach(field -> Assert.isTrue(getValidSearchMatchFields().contains(field), String.format("Search match field \"%s\" is not supported.", field)));
}
 
Example 12
Source File: ObjectStreamClass.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Aggregate the ProtectionDomains of all the classes that separate
 * a concrete class {@code cl} from its ancestor's class declaring
 * a constructor {@code cons}.
 *
 * If {@code cl} is defined by the boot loader, or the constructor
 * {@code cons} is declared by {@code cl}, or if there is no security
 * manager, then this method does nothing and {@code null} is returned.
 *
 * @param cons A constructor declared by {@code cl} or one of its
 *             ancestors.
 * @param cl A concrete class, which is either the class declaring
 *           the constructor {@code cons}, or a serializable subclass
 *           of that class.
 * @return An array of ProtectionDomain representing the set of
 *         ProtectionDomain that separate the concrete class {@code cl}
 *         from its ancestor's declaring {@code cons}, or {@code null}.
 */
private ProtectionDomain[] getProtectionDomains(Constructor<?> cons,
                                                Class<?> cl) {
    ProtectionDomain[] domains = null;
    if (cons != null && cl.getClassLoader() != null
            && System.getSecurityManager() != null) {
        Class<?> cls = cl;
        Class<?> fnscl = cons.getDeclaringClass();
        Set<ProtectionDomain> pds = null;
        while (cls != fnscl) {
            ProtectionDomain pd = cls.getProtectionDomain();
            if (pd != null) {
                if (pds == null) pds = new HashSet<>();
                pds.add(pd);
            }
            cls = cls.getSuperclass();
            if (cls == null) {
                // that's not supposed to happen
                // make a ProtectionDomain with no permission.
                // should we throw instead?
                if (pds == null) pds = new HashSet<>();
                else pds.clear();
                pds.add(noPermissionsDomain());
                break;
            }
        }
        if (pds != null) {
            domains = pds.toArray(new ProtectionDomain[0]);
        }
    }
    return domains;
}
 
Example 13
Source File: NonBlockingRouterTest.java    From ambry with Apache License 2.0 5 votes vote down vote up
/**
 * Polls all managers at regular intervals until the operation is complete or timeout is reached
 * @param futureResult {@link FutureResult} that needs to be tested for completion
 * @throws InterruptedException
 */
private void awaitOpCompletionOrTimeOut(FutureResult futureResult) throws InterruptedException {
  int timer = 0;
  List<RequestInfo> allRequests = new ArrayList<>();
  Set<Integer> allDropped = new HashSet<>();
  while (timer < AWAIT_TIMEOUT_MS / 2 && !futureResult.completed()) {
    pollOpManager(allRequests, allDropped);
    Thread.sleep(50);
    timer += 50;
    allRequests.clear();
    allDropped.clear();
  }
}
 
Example 14
Source File: InstructorProcessor.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
public void postProcess(ProcessorState state) throws Exception {
    Map<String, Set<String>> instructorMap = getInstructorMap(state);

    for (String enrollmentSetEid : instructorMap.keySet()) {
        if (!cmService.isEnrollmentSetDefined(enrollmentSetEid)) {
            log.error("can't sync instructors no enrollment set exists with eid: {}", enrollmentSetEid);
            continue;
        }

        Set<String> newInstructorElements = instructorMap.get(enrollmentSetEid);
        Set<String> newUserEids = new HashSet<>();
        newUserEids.addAll(newInstructorElements);

        EnrollmentSet enrollmentSet = cmService.getEnrollmentSet(enrollmentSetEid);

        Set<String> officialInstructors = enrollmentSet.getOfficialInstructors();
        if (officialInstructors == null) {
            officialInstructors = new HashSet<>();
            enrollmentSet.setOfficialInstructors(officialInstructors);
        }
        officialInstructors.clear();
        officialInstructors.addAll(newUserEids);
        try {
            cmAdmin.updateEnrollmentSet(enrollmentSet);
        } catch (Exception e) {
            log.error("can't save instructor enrollment set", e);
        }
    }
}
 
Example 15
Source File: ExecutionVertex.java    From Flink-CEPplus with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the location preferences of the vertex's current task execution, as determined by the locations
 * of the predecessors from which it receives input data.
 * If there are more than MAX_DISTINCT_LOCATIONS_TO_CONSIDER different locations of source data, this
 * method returns {@code null} to indicate no location preference.
 *
 * @return The preferred locations based in input streams, or an empty iterable,
 *         if there is no input-based preference.
 */
public Collection<CompletableFuture<TaskManagerLocation>> getPreferredLocationsBasedOnInputs() {
	// otherwise, base the preferred locations on the input connections
	if (inputEdges == null) {
		return Collections.emptySet();
	}
	else {
		Set<CompletableFuture<TaskManagerLocation>> locations = new HashSet<>(getTotalNumberOfParallelSubtasks());
		Set<CompletableFuture<TaskManagerLocation>> inputLocations = new HashSet<>(getTotalNumberOfParallelSubtasks());

		// go over all inputs
		for (int i = 0; i < inputEdges.length; i++) {
			inputLocations.clear();
			ExecutionEdge[] sources = inputEdges[i];
			if (sources != null) {
				// go over all input sources
				for (int k = 0; k < sources.length; k++) {
					// look-up assigned slot of input source
					CompletableFuture<TaskManagerLocation> locationFuture = sources[k].getSource().getProducer().getCurrentTaskManagerLocationFuture();
					// add input location
					inputLocations.add(locationFuture);
					// inputs which have too many distinct sources are not considered
					if (inputLocations.size() > MAX_DISTINCT_LOCATIONS_TO_CONSIDER) {
						inputLocations.clear();
						break;
					}
				}
			}
			// keep the locations of the input with the least preferred locations
			if (locations.isEmpty() || // nothing assigned yet
					(!inputLocations.isEmpty() && inputLocations.size() < locations.size())) {
				// current input has fewer preferred locations
				locations.clear();
				locations.addAll(inputLocations);
			}
		}

		return locations.isEmpty() ? Collections.emptyList() : locations;
	}
}
 
Example 16
Source File: PersistentClassIndexScopesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testOverruningClassIndexScopes() throws IOException, InterruptedException {
    final ClassIndexImpl index = ClassIndexManager.getDefault().getUsagesQuery(src.toURL(), true);
    assertNotNull(index);
    final List<Document> res = new ArrayList<>(PKG_COUNT*CLZ_IN_PKG_COUNT);
    Set<ClassIndex.SearchScopeType> scopes = new HashSet<>();
    scopes.add(ClassIndex.SearchScope.SOURCE);
    index.getDeclaredElements(
            "", //NOI18N
            ClassIndex.NameKind.PREFIX,
            scopes,
            null,
            Identity.<Document>getInstance(),
            res);
    assertEquals(PKG_COUNT*CLZ_IN_PKG_COUNT, res.size());
    res.clear();
    scopes.clear();
    final Set<String> pkgs = new HashSet<>();
    index.getPackageNames("", true, pkgs);
    assertEquals(PKG_COUNT, pkgs.size());
    scopes.add(ClassIndex.createPackageSearchScope(
        ClassIndex.SearchScope.SOURCE,
        pkgs.toArray(new String[pkgs.size()])));
    index.getDeclaredElements(
            "", //NOI18N
            ClassIndex.NameKind.PREFIX,
            scopes,
            null,
            Identity.<Document>getInstance(),
            res);
    assertEquals(PKG_COUNT*CLZ_IN_PKG_COUNT, res.size());
}
 
Example 17
Source File: SupportedQueryTypesTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private int doQueryNames(QueryExp query, Set<ObjectName> referenceSet) {
    int errorCount = 0;
    System.out.println(" <*> Perform queryNames call ");

    try {
        // Call queryNames on the remote MBeanServer
        Set<ObjectName> remoteSet =  mbsc.queryNames(null, query);

        // Compare the 2 Set<ObjectName>
        errorCount += checkSet(remoteSet, referenceSet);

        // Cleaning
        remoteSet.clear();

    } catch (Exception e) {
        Utils.printThrowable(e, true);
        errorCount++;
    }

    if ( errorCount == 0 ) {
        System.out.println("\t(OK)");
    } else {
        System.out.println("\t(ERROR) Query failed");
    }

    return errorCount;
}
 
Example 18
Source File: CacheIndexTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testAddRemoveNotExistingParentContainsFiles() throws MalformedURLException, IOException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
    CacheIndex ci = new CIndex();
    Map<File, Set<File>> index = getIndex(ci);
    index.clear();

    File root = new File(wc, "root");

    File folder1 =   new File(root,      "folder1");
    File folder11 =  new File(folder1,     "folder11");
    File folder111 = new File(folder11,     "folder111");
    File file111_1 = new File(folder111,      "file111_1");
    File folder112 = new File(folder11,     "folder112");
    File folder12 =  new File(folder1,     "folder12");
    File file12_1 =  new File(folder12,     "file12_1");
    folder111.mkdirs();
    folder112.mkdirs();
    folder12.mkdirs();
    file111_1.createNewFile();
    file12_1.createNewFile();

    // add file111_1 -> all versioned parents will be added
    Set<File> s = new HashSet<File>();
    s.add(file111_1);
    ci.add(folder111, s);
    s.clear();
    s.add(file12_1);
    ci.add(folder12, s);
    checkParents(index, file111_1, file12_1);

    assertValueSet(index.get(wc), new File[] {root});
    assertValueSet(index.get(root), new File[] {folder1});
    assertValueSet(index.get(folder1), new File[] {folder11, folder12});
    assertValueSet(index.get(folder11), new File[] {folder111});
    assertValueSet(index.get(folder12), new File[] {file12_1});
    assertValueSet(index.get(folder111), new File[] {file111_1});

    // remove file112_1 which isn't indexed -> folder111 remains
    s = new HashSet<File>();
    ci.add(folder112, s);
    checkParents(index, file111_1, file12_1);

    assertValueSet(index.get(wc), new File[] {root});
    assertValueSet(index.get(root), new File[] {folder1});
    assertValueSet(index.get(folder1), new File[] {folder11, folder12});
    assertValueSet(index.get(folder11), new File[] {folder111});
    assertValueSet(index.get(folder12), new File[] {file12_1});
    assertValueSet(index.get(folder111), new File[] {file111_1});
}
 
Example 19
Source File: FactDistinctColumnsMapper.java    From kylin-on-parquet-v2 with Apache License 2.0 4 votes vote down vote up
public void resetIfShortOfMem() {
    if (MemoryBudgetController.getSystemAvailMB() < resetThresholdMB) {
        for (Set<String> set : colValueSets.values())
            set.clear();
    }
}
 
Example 20
Source File: AgreeSetGenerator.java    From metanome-algorithms with Apache License 2.0 4 votes vote down vote up
public Set<IntList> computeMaximumSetsAlternative(List<StrippedPartition> partitions) {

        if (this.debugSysout) {
            System.out.println("\tstartet calculation of maximal partitions");
        }
        long start = System.currentTimeMillis();

        Set<IntList> sortedPartitions = new TreeSet<IntList>(new ListComparator());
        for (StrippedPartition p : partitions) {
            sortedPartitions.addAll(p.getValues());
        }
        Iterator<IntList> it = sortedPartitions.iterator();
        Int2ObjectMap<Set<IntList>> maxSets = new Int2ObjectOpenHashMap<Set<IntList>>();
        long remainingPartitions = sortedPartitions.size();
        if (this.debugSysout) {
            System.out.println("\tNumber of Partitions: " + remainingPartitions);
        }
        if (it.hasNext()) {
            IntList actuelList = it.next();
            int minSize = actuelList.size();
            Set<IntList> set = new HashSet<IntList>();
            set.add(actuelList);
            while ((actuelList = it.next()) != null && (actuelList.size() == minSize)) {
                if (this.debugSysout) {
                    System.out.println("\tremaining: " + --remainingPartitions);
                }
                set.add(actuelList);
            }
            maxSets.put(minSize, set);
            if (actuelList != null) {
                maxSets.put(actuelList.size(), new HashSet<IntList>());
                if (this.debugSysout) {
                    System.out.println("\tremaining: " + --remainingPartitions);
                }
                this.handleList(actuelList, maxSets, true);
                while (it.hasNext()) {
                    actuelList = it.next();
                    if (this.debugSysout) {
                        System.out.println("\tremaining: " + --remainingPartitions);
                    }
                    if (!maxSets.containsKey(actuelList.size()))
                        maxSets.put(actuelList.size(), new HashSet<IntList>());
                    this.handleList(actuelList, maxSets, true);
                }
            }
        }

        long end = System.currentTimeMillis();
        if (this.debugSysout)
            System.out.println("\tTime needed: " + (end - start));

        Set<IntList> max = this.mergeResult(maxSets);
        maxSets.clear();
        sortedPartitions.clear();

        return max;
    }