001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.collections4.properties;
019
020import java.util.AbstractMap;
021import java.util.AbstractMap.SimpleEntry;
022import java.util.Enumeration;
023import java.util.LinkedHashSet;
024import java.util.Map;
025import java.util.Properties;
026import java.util.Set;
027import java.util.stream.Collectors;
028import java.util.stream.Stream;
029
030import org.apache.commons.collections4.iterators.IteratorEnumeration;
031
032/**
033 * A drop-in replacement for {@link Properties} for sorting keys.
034 * <p>
035 * Overrides {@link Properties#keys()} to sort keys. Allows other methods on the superclass to work with sorted keys.
036 * </p>
037 *
038 * @see SortedPropertiesFactory#INSTANCE
039 * @since 4.2
040 */
041public class SortedProperties extends Properties {
042
043    private static final long serialVersionUID = 1L;
044
045    @Override
046    public Set<Map.Entry<Object, Object>> entrySet() {
047        final Stream<SimpleEntry<Object, Object>> stream = sortedKeys().map(k -> new AbstractMap.SimpleEntry<>(k, getProperty(k)));
048        return stream.collect(Collectors.toCollection(LinkedHashSet::new));
049    }
050
051    @Override
052    public synchronized Enumeration<Object> keys() {
053        return new IteratorEnumeration<>(sortedKeys().collect(Collectors.toList()).iterator());
054    }
055
056    private Stream<String> sortedKeys() {
057        return keySet().stream().map(Object::toString).sorted();
058    }
059}