【问题标题】:sorting a List<Map<String, String>>排序 List<Map<String, String>>
【发布时间】:2016-11-25 12:34:00
【问题描述】:

我有一个字符串映射列表:

List<Map<String, String>> list = new ArrayList<Map<String, String>>();

这将填充以下内容:

Map<String, String> action1 = new LinkedHashMap<>();
map.put("name", "CreateFirstName");
map.put("nextAction", "CreateLastName");

Map<String, String> action2 = new LinkedHashMap<>();
map.put("name", "CreateAddress");
map.put("nextAction", "CreateEmail");

Map<String, String> action3 = new LinkedHashMap<>();
map.put("name", "CreateLastName");
map.put("nextAction", "CreateAddress");

Map<String, String> action4 = new LinkedHashMap<>();
map.put("name", "CreateEmail");

list.add(action1);
list.add(action2);
list.add(action3);
list.add(action4);

action4 没有 nextAction,因为它是最后一个操作,但给它一个 nextAction 可能更容易,它是没有下一步操作的占位符?

问题:如何对列表进行排序,以便操作有序? 即:一个动作的nextAction,与列表中下一个动作的名称相同。

【问题讨论】:

  • 为什么不使用包含CreateFirstName, CreateLastName, CreateAddress, CreateEmail 的List&lt;String&gt;?或Map&lt;String, String&gt;,其中键是name 值,值是nextAction?
  • 哎呀。那是一个错字。 CreateLastName 的 nextAction 应该是 CreateEmail。
  • 已更新。没有 createEmailName。
  • 这听起来像是 enum 的工作
  • 为什么要使用Map?您应该创建自己的类型,它会使这变得容易得多。一个Action 可以有一个String name 和一个Action nextAction。当一个动作完成时,如果一个操作系统可用,它会触发下一个动作。您想要的行为听起来类似于chain of responsibility 模式

标签: java list sorting comparator


【解决方案1】:

虽然这似乎是XY-Problem 的一个例子,而且这个地图列表肯定不是一个“设计精美的数据模型”,而且很可能有一个在很多方面都“更好”的表示(尽管没有人可以就“最佳”模型可能是什么提出建议,只要不知道总体目标),这是您手头的任务,下面是如何解决它:

首先,您必须确定排序列表的第一个元素。这正是具有"name" 条目的映射,该条目不显示为任何其他映射的"nextAction" 条目。

获得第一张地图后,您可以将其添加到(排序的)列表中。然后,确定下一个元素归结为找到其"name" 与前一个映射的"nextAction" 相同的映射。要快速找到这些后继者,您可以构建一个映射,将每个 "name" 条目映射到映射本身。

这是这种排序方法的基本实现:

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class SortListWithMaps
{
    public static void main(String[] args)
    {
        List<Map<String, String>> list = new ArrayList<Map<String, String>>();

        Map<String, String> action1 = new LinkedHashMap<>();
        action1.put("name", "CreateFirstName");
        action1.put("nextAction", "CreateLastName");

        Map<String, String> action2 = new LinkedHashMap<>();
        action2.put("name", "CreateAddress");
        action2.put("nextAction", "CreateEmail");

        Map<String, String> action3 = new LinkedHashMap<>();
        action3.put("name", "CreateLastName");
        action3.put("nextAction", "CreateAddress");

        Map<String, String> action4 = new LinkedHashMap<>();
        action4.put("name", "CreateEmail");

        list.add(action1);
        list.add(action2);
        list.add(action3);
        list.add(action4);        

        // Make it a bit more interesting...
        Collections.shuffle(list);

        System.out.println("Before sorting");
        for (Map<String, String> map : list)
        {
            System.out.println(map);
        }

        List<Map<String, String>> sortedList = sort(list);

        System.out.println("After sorting");
        for (Map<String, String> map : sortedList)
        {
            System.out.println(map);
        }
    }

    private static List<Map<String, String>> sort(
        List<Map<String, String>> list)
    {
        // Compute a map from "name" to the actual map
        Map<String, Map<String, String>> nameToMap = 
            new LinkedHashMap<String, Map<String,String>>();
        for (Map<String, String> map : list)
        {
            String name = map.get("name");
            nameToMap.put(name, map);
        }

        // Determine the first element for the sorted list. For that,
        // create the set of all names, and remove all of them that
        // appear as the "nextAction" of another entry
        Set<String> names = 
            new LinkedHashSet<String>(nameToMap.keySet());
        for (Map<String, String> map : list)
        {
            String nextAction = map.get("nextAction");
            names.remove(nextAction);
        }
        if (names.size() != 1)
        {
            System.out.println("Multiple possible first elements: " + names);
            return null;
        }

        // Insert the elements, in sorted order, into the result list
        List<Map<String, String>> result = 
            new ArrayList<Map<String, String>>();
        String currentName = names.iterator().next();
        while (currentName != null)
        {
            Map<String, String> element = nameToMap.get(currentName);
            result.add(element);
            currentName = element.get("nextAction");
        }
        return result;
    }
}

【讨论】:

  • 这个实现非常适合我正在尝试做的事情。谢谢!
【解决方案2】:

不要使用Map 来存储动作的属性(name 和nextAction),而是创建由这些属性组成的您自己的类型:

class Action {
    private String name;
    //nextAction

    public void perform() {
        //do current action
        //use nextAction to perform the next action
    }
}

nextAction 现在可以作为对下一个操作的引用:

abstract class Action implements Action {
    private String name;
    private Action nextAction;

    public Action(String name) {
        this.name = name;
    }

    public final void perform() {
        perform(name);
        nextAction.perform();
    }

    protected abstract void perform(String name);
}

您现在可以通过子类型 Action 类来创建您的操作:

class CreateFirstName extends Action {
    public CreateFirstName(Action nextAction) {
        super("CreateFirstName", nextAction);
    }

    protected final void perform(String name) {
        System.out.println("Performing " + name);
    }
}

并将它们链接在一起:

Action action = new CreateFirstName(new CreateLastName(new CreateEmail(...)));

嵌套表达式可能会变得非常混乱,但我们稍后会讨论。这里有一个更大的问题。

action4 没有 nextAction,因为它是最后一个动作,但给它一个 nextAction 可能更容易,它是没有下一步动作的占位符

同样的问题也适用于上面的代码。

现在,由于构造函数Action(String, Action),每个动作必须有一个下一个动作。我们可以采取简单的路线并传入一个占位符以表示没有下一步操作(null 是最简单的路线):

class End extends Action {
    public End() {
        super("", null);
    }
}

然后做一个空检查:

//class Action
public void perform() {
        perform(name);

        if(nextAction != null) {
            nextAction.perform(); //performs next action
        }
    }

但这将是一个code smell。您可以在此处停止阅读并使用简单的修复方法,或者继续下面的更多参与(和教育)路线。


当您使用 null 时,很有可能会成为代码异味的受害者。虽然它并不适用于所有情况(由于 Java 的 null 安全性差),但您应该尝试avoid null if possible。相反,请重新考虑您的设计,如本例所示。如果一切都失败了,请使用Optional。

最后一个动作与其他动作不同。它仍然可以像其他一样执行,但它有不同的属性要求。

这意味着它们可以共享相同的行为抽象,但在定义属性时必须有所不同:

interface Action {
    void perform();
}

abstract class ContinuousAction implements Action {
    private String name;
    private Action nextAction;

    public ContinuousAction(String name) {
        this.name = name;
    }

    public final void perform() {
        perform(name);
        nextAction.perform();
    }

    protected abstract void perform(String name);
}

abstract class PlainAction implements Action {
    private String name;

    public PlainAction(String name) {
        this.name = name;
    }

    public final void perform() {
        perform(name);
    }

    protected abstract void perform(String name);
}

最后一个动作将扩展PlainAction,而其他动作将扩展ContinuousAction。

最后,防止长链:

new First(new Second(new Third(new Fourth(new Fifth(new Sixth(new Seventh(new Eighth(new Ninth(new Tenth())))))))))

您可以在每个具体动作中指定下一个动作:

class CreateFirstName extends ContinuousAction {
    public CreateFirstName() {
         super("CreateFirstName", new CreateLastName());
    }

    //...
}

class CreateLastName extends ContinuousAction {
    public CreateLastName() {
        super("CreateLastName", new CreateEmail());
    }

    //...
}

class CreateEmail extends PlainAction {
    public CreateEmail() {
         super("CreateEmail");
    }

    //...
}

ContinuousAction 和 PlainAction 可以进一步抽象。它们都是命名动作(它们有名称),并且该属性以 samw 方式影响它们的contract(将其传递给template methodprocess(String)):

abstract class NamedAction implements Action {
    private String name;

    public NamedAction(String name) {
        this.name = name;
    }

    public final void perform() {
        perform(name);
    }

    protected abstract void perform(String name);
}

//class ContinuousAction extends NamedAction
//class PlainAction extends NamedAction

【讨论】:

    猜你喜欢
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-22
    • 2020-01-26
    • 1970-01-01
    相关资源
    最近更新 更多