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 /** 046 * Constructs a new instance. 047 */ 048 public SortedProperties() { 049 // empty 050 } 051 052 @Override 053 public Set<Map.Entry<Object, Object>> entrySet() { 054 final Stream<SimpleEntry<Object, Object>> stream = sortedKeys().map(k -> new AbstractMap.SimpleEntry<>(k, getProperty(k))); 055 return stream.collect(Collectors.toCollection(LinkedHashSet::new)); 056 } 057 058 @Override 059 public synchronized Enumeration<Object> keys() { 060 return new IteratorEnumeration<>(sortedKeys().collect(Collectors.toList()).iterator()); 061 } 062 063 private Stream<String> sortedKeys() { 064 return keySet().stream().map(Object::toString).sorted(); 065 } 066}