Java Stream HOW TO.Stream()

Java Stream HOW TO.Stream(),java,stream,set,Java,Stream,Set,我正在努力和谷歌搜索,但不能得到它的权利。如何用stream编写这个 private final ConcurrentMap<UUID, Expression> alleMap = new ConcurrentHashMap<>(1000); private String[] getAllDatabases() { Set<String> allDatabases = new HashSet<>(); for (Entr

我正在努力和谷歌搜索,但不能得到它的权利。如何用stream编写这个

private final ConcurrentMap<UUID, Expression> alleMap = new ConcurrentHashMap<>(1000);

 private String[] getAllDatabases()
  {
     Set<String> allDatabases = new HashSet<>();
     for (Entry<UUID, Expression> entry : alleMap.entrySet())
     {
        allDatabases.add(entry.getValue().getChapter().getDatabaseName());
     }
     List<String> allDatabasesList = new ArrayList<>(allDatabases);
     String[] result = new String[allDatabases.size()];
     for (int i=0; i < result.length; i++)
     {
        result[i] = allDatabasesList.get(i);
     }  
     return result;
  }


alleMap.values().stream().???
private final ConcurrentMap alleMap=new ConcurrentHashMap(1000);
私有字符串[]getAllDatabases()
{
Set allDatabases=new HashSet();
for(条目:alleMap.entrySet())
{
添加(entry.getValue().getChapter().getDatabaseName());
}
List allDatabasesList=新建ArrayList(所有数据库);
字符串[]结果=新字符串[allDatabases.size()];
for(int i=0;i

我需要数组的原因是我正在编写一个Swing应用程序,需要字符串[]来回答JOptionPane问题。

从不需要数组开始。它们是低级的、不灵活的结构,不能很好地处理泛型,通常不应该使用它们,除非你真的知道自己在做什么,并且愿意接受一些痛苦来适应它

流是一种工具。这不是一个普遍的进步。如果有急迫的需要,一定要顺其自然。但是,不要因为你认为流在某种程度上“更好”,就用流取代一切。做你觉得舒服的事:)

如果必须:

您根本不使用键,只使用值。那么,为什么要为entrySet而烦恼呢?values()将以更少的努力获得您想要的

List<String> alleMap.values().stream()
  .map(e -> e.getChapter().getDataBaseName())
  .collect(Collectors.toList());
List alleMap.values().stream()
.map(e->e.getChapter().getDataBaseName())
.collect(Collectors.toList());

这是相当基本的;也许放下你正在处理的具体案例,先学习一些教程,然后再重新学习,你很快就会掌握窍门。

为你详细介绍:

Set<String> allDatabases = new HashSet<>();
for (Entry<UUID, Expression> entry : alleMap.entrySet()) {
    allDatabases.add(entry.getValue().getChapter().getDatabaseName());
}

请注意
distinct
以复制集合的唯一性。

entry.getValue()将返回表达式。你怎么称呼它?可能有编译错误。我更新了我的问题。表达式对象有一个Chapter对象,这就是为什么我可以调用它的getChapter。它编译。
 List<String> allDatabasesList = new ArrayList<>(allDatabases);
 String[] result = new String[allDatabases.size()];
 for (int i=0; i < result.length; i++) {
    result[i] = allDatabasesList.get(i);
 }  
alleMap.values().stream()
    .map(Expression::getChapter)
    .map(Chapter::getDatabaseName)
    .distinct()
    .toArray(String[]::new);