gpt4 book ai didi

java - 打乱 Java 流对象列表

转载 作者:行者123 更新时间:2023-12-01 19:35:04 25 4
gpt4 key购买 nike

我有一个单词列表:List<Word> words

bean Word是:

public class Word {
private String name;
private String meaning;
...
}

我想对元素进行洗牌以使其具有以下内容:

来自:

{ name: "day", meaning: "giorno"},
{ name: "year", meaning: "anno"},
{ name: "hour", meaning: "ora"}

致:

{ name: "day", meaning: "ora"},
{ name: "year", meaning: "giorno"},
{ name: "hour", meaning: "anno"}

我已经尝试过这个,但我认为有一个更优雅的解决方案:

private List<Word> shuffle(List<Word> words) {
List<String> names = words.stream()
.map(word -> word.getName())
.collect(Collectors.toList());
List<String> meanings = words.stream()
.map(word -> word.getMeaning())
.collect(Collectors.toList());
Collections.shuffle(meanings);

words = new ArrayList<Word>();
for(int i = 0; i<names.size(); i++) {
words.add(new Word(names.get(i), meanings.get(i)));
}

return words;
}

最佳答案

您可以进行就地洗牌。为此,您无需创建额外的 Word 对象。

private void shuffle(List<Word> words) {
List<String> meanings = words.stream()
.map(Word::getMeaning)
.collect(Collectors.toList());
Collections.shuffle(meanings);

for(int i = 0; i < words.size(); i++) {
words.get(i).setMeaning(meanings.get(i));
}
}

关于java - 打乱 Java 流对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58131810/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com