All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.ultreia.java4all.util.SortedProperties Maven / Gradle / Ivy

There is a newer version: 1.2.1
Show newest version
package io.ultreia.java4all.util;

/*-
 * #%L
 * Java Util extends by Ultreia.io
 * %%
 * Copyright (C) 2018 Ultreia.io
 * %%
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Lesser Public License for more details.
 * 
 * You should have received a copy of the GNU General Lesser Public
 * License along with this program.  If not, see
 * .
 * #L%
 */

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;
import java.util.Set;
import java.util.function.Function;

/**
 * Extends {@link Properties} and ensure order on keys (using natural order on {@link #function} method).
 * 

* This means that when you will {@code load} or {@code store} , this order will be used. * Created by tchemit on 29/12/2017. * * @author Tony Chemit - [email protected] */ public class SortedProperties extends Properties { private static final long serialVersionUID = -1L; private Function function = Object::toString; public SortedProperties() { } public SortedProperties(Properties defaults) { super(defaults); } @Override public synchronized Enumeration keys() { List keys = Collections.list(super.keys()); List sortedKeys = sort(keys); return Collections.enumeration(sortedKeys); } @Override public Set stringPropertyNames() { Set stringPropertyNames = super.stringPropertyNames(); List sortedStringPropertyNames = sort(stringPropertyNames); return new LinkedHashSet<>(sortedStringPropertyNames); } @SuppressWarnings("NullableProblems") @Override public Set> entrySet() { List keys = Collections.list(super.keys()); List sortedKeys = sort(keys); List> sortedEntries = new ArrayList<>(super.entrySet()); sortedEntries.sort(Comparator.comparingInt(e->sortedKeys.indexOf(e.getKey()))); return new LinkedHashSet<>(sortedEntries); } @SuppressWarnings("unchecked") public void setFunction(Function function) { this.function = Objects.requireNonNull((Function) function); } private List sort(Collection collection) { List list = collection instanceof List ? (List) collection : new ArrayList<>(collection); list.sort(Comparator.comparing(function)); return list; } }