我正在尝试收集丢弃很少使用的项目的流,如下例所示:
import java.util.*;
import java.util.function.Function;
import static java.util.stream.Collectors.*;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsInAnyOrder;
import org.junit.Test;
@Test
public void shouldFilterCommonlyUsedWords() {
// given
List<String> allWords = Arrays.asList(
"call", "feel", "call", "very", "call", "very", "feel", "very", "any");
// when
Set<String> commonlyUsed = allWords.stream()
.collect(groupingBy(Function.identity(), counting()))
.entrySet().stream().filter(e -> e.getValue() > 2)
.map(Map.Entry::getKey).collect(toSet());
// then
assertThat(commonlyUsed, containsInAnyOrder("call", "very"));
}
Run Code Online (Sandbox Code Playgroud)
我觉得有可能做得更简单 - 我是对的吗?
例如我的列表包含{4,6,6,7,7,8},我想要最终结果= {6,6,7,7}
一种方法是遍历列表并消除唯一值(在这种情况下为4,8).
有没有其他有效的方式而不是循环列表?我问过这个问题,因为我工作的清单非常大?我的代码是
List<Long> duplicate = new ArrayList();
for (int i = 0; i < list.size(); i++) {
Long item = (Long) list.get(i);
if (!duplicate.contains(item)) {
duplicate.add(item);
}
}
Run Code Online (Sandbox Code Playgroud) Set<String> unique = new HashSet<>();
List<String> duplicates = new ArrayList<>();
for (Animal cat: animals) {
if (!unique.add(cat.getName())) {
duplicates.add(cat.getName());
}
}
return duplicates;
Run Code Online (Sandbox Code Playgroud)
我想知道是否有办法简化这个?我是Java流的新手,我尝试使用Map,但我采用了传统的for循环.
private boolean hasDuplicates(Recipe recipe) {
List<Recipe> currentRecipes = new ArrayList<>();
Stream.of(this.breakfast, this.lunch, this.dinner).forEach(meal -> {
currentRecipes.add(meal.getRecipe());
currentRecipes.add(meal.getSnack());
});
currentRecipes.add(this.snack);
return currentRecipes.contains(recipe);
};
}
Run Code Online (Sandbox Code Playgroud)
// 想象一下所有字段的 getter 和 setter。
public class Menuplan {
private Meal breakfast;
private Meal lunch;
private Meal dinner;
private Recipe snack;
}
public class Meal {
private Recipe recipe;
private Reicpe snack;
}
Run Code Online (Sandbox Code Playgroud)
如果 Menuplan 已经分配了给定的食谱(作为零食或食谱),我使用上述方法进行测试。
我想知道是否有更优雅/更短的方法来编写函数。