如何从对象流中统一对象的集合

时间:2019-11-23 17:16:36

标签: java collections java-stream flatten

我有这个CasaDeBurrito课:

public class CasaDeBurritoImpl implements OOP.Provided.CasaDeBurrito {

    private Integer id;
    private String name;
    private Integer dist;
    private Set<String> menu;
    private Map<Integer, Integer> ratings;
...
}

和这个教授类:(应该是一个s)

public class ProfessorImpl implements OOP.Provided.Profesor {

    private Integer id;
    private String name;
    private List<CasaDeBurrito> favorites;
    private Set<Profesor> friends;

    private Comparator<CasaDeBurrito> ratingComparator = (CasaDeBurrito c1, CasaDeBurrito c2) ->
    {
        if (c1.averageRating() == c2.averageRating()) {
            if (c1.distance() == c2.distance()) {
                return Integer.compare(c1.getId(), c2.getId());
            }
            return Integer.compare(c1.distance(), c2.distance());
        }
        return Double.compare(c2.averageRating(), c1.averageRating());
    };

    private Predicate<CasaDeBurrito> isAvgRatingAbove(int rLimit) {
        return c -> c.averageRating() >= rLimit;
    };

    public Collection<CasaDeBurrito> 
    filterAndSortFavorites(Comparator<CasaDeBurrito> comp, Predicate<CasaDeBurrito> p) {
            return favorites.stream().filter(p).sorted(comp).collect(Collectors.toList());
    }

    public Collection<CasaDeBurrito> favoritesByRating(int rLimit) {
            return filterAndSortFavorites(ratingComparator, isAvgRatingAbove(rLimit));
    }
}

我想实现一个函数,该函数获取Profesor prof,并统一所有favorites朋友的prof的所有CasaDeBurrito集,并按ID排序,并带有流。 因此,我希望按评分(带有favoritesByRating)收集所有喜欢的public Collection<CasaDeBurrito> favoritesByRating(Profesor p) { Stream ret = p.getFriends().stream() .<*some Intermediate Operations*>. .forEach(y->y.concat(y.favoritesByRating(0)) .<*some Intermediate Operations*>. .collect(toList()); return ret; } 餐厅。

例如:

df.groupby('Year').agg({'Count': 'sum'}).reset_index().max()

2 个答案:

答案 0 :(得分:1)

您想要一个a collection of all CasaDeBurrito favorites by friends sorted by name,所以我想说Map<String, List<CasaDeBurrito>>是您所需要的,每个键都是朋友的名字,而值是他喜欢使用CasaDeBurrito的列表favoritesByRating方法,全部按名称排序(使用TreeMap

public Map<String, List<CasaDeBurrito>> favoritesByRating(Profesor p) {
    return p.getFriends().stream()
            .collect(toMap(Profesor::getName, prof -> prof.favoritesByRating(0), (i, j) -> i, TreeMap::new));
}

如果您只想列出朋友喜欢的CasaDeBurrito的列表,请使用flatMap

public List<CasaDeBurrito> favoritesByRating(Profesor p) {
    return p.getFriends().stream()
            .flatMap(prof -> prof.favoritesByRating(0).stream())
            .collect(toList());
}

答案 1 :(得分:0)

所以我不知道如何正确地提出问题,但是我设法将评论和答案与需要的内容联系起来。 我按ID对朋友进行排序,并在他的评论here中以@Alex Faster分享的形式创建了一个收藏流,并按照上面的建议展平了该流。

    public static string Safe(string s)
    {
        s = s
            .Replace("<", "ooopen-angle-brackettt") // must come first
            .Replace(">", "ccclose-angle-brackettt") // must come first
            //.Replace(",", "<comma>") // allow
            //.Replace(".", "<dot>") // allow
            //.Replace(":", "<colon>") // allow
            .Replace(";", "<semi-colon>")
            .Replace("{", "<open-curly-bracket>")
            .Replace("}", "<close-curly-bracket>")
            //.Replace("[", "<open-square-bracket>") // allow
            //.Replace("]", "<close-square-bracket>") // allow
            .Replace("(", "<open-bracket>")
            .Replace(")", "<close-bracket>")
            .Replace("!", "<exclamation-mark>")
            .Replace("@", "<at>")
            .Replace("#", "<hash>")
            .Replace("$", "<dollar>")
            .Replace("%", "<percent>")
            .Replace("^", "<hat>")
            .Replace("&", "<and>")
            .Replace("*", "<asterisk>")
            //.Replace("-", "<dash>") // allow
            //.Replace("_", "<underscore>") // allow
            .Replace("+", "<plus>")
            .Replace("=", "<equals>")
            .Replace("\\", "<forward-slash>")
            .Replace("\"", "<double-quote>")
            .Replace("'", "<single-quote>")
            .Replace("/", "<forward-slash>")
            .Replace("?", "<question-mark>")
            .Replace("|", "<pipe>")
            .Replace("~", "<tilde>")
            .Replace("`", "<backtick>")
            .Replace("ooopen-angle-brackettt", "<open-angle-bracket>")
            .Replace("ccclose-angle-brackettt", "<close-angle-bracket>");
        // all working upto here. broken below:

        Regex itemRegex = new Regex(@"[^A-Za-z0-9<>[\]:.,_\s-]", RegexOptions.Compiled);
        foreach (Match itemMatch in itemRegex.Matches(s))
        {
            // the reason for [0] and [1] is that I read that unicode consists of 2 characters
            s = s.Replace(
                itemMatch.ToString(),
                "<U+" +
                    (((int)(itemMatch.ToString()).ToCharArray()[0]).ToString("X4")).ToString() +
                    (((int)(itemMatch.ToString()).ToCharArray()[1]).ToString("X4")).ToString() +
                ">"
            );
        }
        return s;
    }

我将再次编辑我的问题,以使其更加清晰。