我找到了通过POJO中的某个字段名称对对象进行分组的代码.以下是代码:
public class Temp {
static class Person {
private String name;
private int age;
private long salary;
Person(String name, int age, long salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
@Override
public String toString() {
return String.format("Person{name='%s', age=%d, salary=%d}", name, age, salary);
}
}
public static void main(String[] args) {
Stream<Person> people = Stream.of(new Person("Paul", 24, 20000),
new Person("Mark", 30, 30000),
new Person("Will", 28, 28000),
new Person("William", 28, 28000));
Map<Integer, List<Person>> peopleByAge;
peopleByAge = people …Run Code Online (Sandbox Code Playgroud) 考虑以下WorkExperience课程:
public class WorkExperience {
private int year;
private List<Skills> skill;
public WorkExperience(int year, List<Skills> skill) {
this.year = year;
this.skill = skill;
}
//getter setter
}
public class Skills {
private String skills;
public Skills(String skills) {
this.skills = skills;
}
@Override
public String toString() {
return "Skills [skills=" + skills + "]";
}
}
Run Code Online (Sandbox Code Playgroud)
假设我希望按年份按照我的技能进行分组,这就是我们groupBy今年的表现:
public static void main(String[] args) {
List<Skills> skillSet1 = new ArrayList<>();
skillSet1.add(new Skills("Skill-1"));
skillSet1.add(new Skills("Skill-2"));
skillSet1.add(new Skills("Skill-3"));
List<Skills> skillSet2 …Run Code Online (Sandbox Code Playgroud) 我接触到了一个新功能,因为java-9被称为Collectors.flatMapping分组或分区的下游.如(例子来自这里):
List<List<Integer>> list = Arrays.asList(
Arrays.asList(1, 2, 3, 4, 5, 6),
Arrays.asList(7, 8, 9, 10));
Map<Integer, List<Integer>> map =list.stream()
.collect(Collectors.groupingBy(
Collection::size,
Collectors.flatMapping(
l -> l.stream().filter(i -> i % 2 == 0),
Collectors.toList())));
Run Code Online (Sandbox Code Playgroud)
{4 = [8,10],6 = [2,4,6]}
这是一个相当优雅的方式,只使用3个收藏家.我需要在java-8中重写收集器,但尚不支持.我尝试使用6种收集器,这种收集器使用起来 非常广泛,我无法找到使用较少的收集器的方法:
Map<Integer, List<Integer>> map = list.stream()
.collect(Collectors.groupingBy(
Collection::size,
Collectors.collectingAndThen(
Collectors.mapping(
l -> l.stream().filter(i -> i % 2 == 0).collect(Collectors.toList()),
Collectors.toList()),
i -> i.stream().flatMap(j -> j.stream()).collect(Collectors.toList()))));
Run Code Online (Sandbox Code Playgroud)
是否有一个更短的仅使用更好的方法的Java-8 ?
I have some code that I need help with ... I'm trying to build a map using two maps as a source and at the same time using java lambdas
Map<String, List<String>> motorsMapping = new HashMap<>();
motorsMapping.put("CAR", Collections.singletonList("AUDI"));
motorsMapping.put("CAR_AND_BIKE", Arrays.asList("AUDI", "BMW"));
motorsMapping.put("BIKE", Collections.singletonList("BMW"));
Map<String, List<String>> models = new HashMap<>();
models.put("AUDI", Arrays.asList("A1", "Q2"));
models.put("BMW", Arrays.asList("X1", "X5"));
motorsMapping.keySet().forEach(key -> {
Map<String, List<String>> result = new HashMap<>();
result.put(key, new ArrayList<>());
motorsMapping.get(key).forEach(value -> models.getOrDefault(value, Collections.emptyList()).forEach(property -> result.get(key).add(property)));
});
Run Code Online (Sandbox Code Playgroud)
I can do that with the …
我有这门课.
class Assignment {
private Integer index;
private List<Quantity> quantities;
}
Run Code Online (Sandbox Code Playgroud)
然后,我有一个来自该类的对象列表.
List<Assigment> assignments = new ArrayList<>();
Run Code Online (Sandbox Code Playgroud)
有没有办法创建一个Map包含索引Assignment和List<Quantity>as值的方法?
这是我到目前为止所尝试的.
assignments.stream().collect(groupingBy(Assignment::getIndex));
Run Code Online (Sandbox Code Playgroud)
但这给了我一个Map<Integer, List<Assignment>>,我想要一个Map<Integer, List<Quantity>>.
我已经尝试过使用forEach方法 - 它可以工作 - 但我确信必须有一种方法可以在一个衬里中完成它 - 或者至少只使用collect和groupingBy方法
所以我有一段代码,我在迭代一个数据列表.每一个都ReportData包含一个带有一个Long caseId和一个的案例Ruling.每个Ruling都有一个或多个Payment.我希望Map将caseIdas键和付款组作为值(即a Map<Long, Set<Payments>>).
案例在行之间并不是唯一的,但案例是.
换句话说,我可以有几个具有相同大小写的行,但它们将具有唯一的规则.
下面的代码给我一个Map<Long, Set<Set<Payments>>>几乎我想要的东西,但我一直在努力找到在给定上下文中flatMap最终集合的正确方法.我一直在做着使用这个映射使逻辑正常工作的解决方法,但是我非常想修复算法以将这组付款正确地组合成一个集合,而不是创建一组集合.
虽然使用Java流进行flatMapping似乎是一个有点热门的话题,但我一直在搜索并找不到相同类型的迭代问题.
rowData.stream()
.collect(Collectors.groupingBy(
r -> r.case.getCaseId(),
Collectors.mapping(
r -> r.getRuling(),
Collectors.mapping(ruling->
ruling.getPayments(),
Collectors.toSet()
)
)));
Run Code Online (Sandbox Code Playgroud) 我的班有两个领域:
MyKey - 我想要分组的关键Set<MyEnum> - 我想要展平和合并的集合.我有一个这样的对象的列表,我想要的是获得一个Map<MyKey, Set<MyEnum>使用此键从对象的所有myEnums连接的值.
例如,如果我有三个对象:
myKey: key1, myEnums: [E1]myKey: key1, myEnums: [E2]myKey: key2, myEnums: [E1, E3]预期结果应该是:
key1 => [E1, E2], key2 => [E1, E3]
我想出了这段代码:
Map<MyKey, Set<MyEnum>> map = myObjs.stream()
.collect(Collectors.groupingBy(
MyType::getMyKey,
Collectors.reducing(
new HashSet<MyEnum>(),
MyType::getMyEnums,
(a, b) -> {
a.addAll(b);
return a;
})));
Run Code Online (Sandbox Code Playgroud)
它有两个问题:
HashSet减少的内部似乎在所有键之间共享.这就是说上面例子的实际运行结果是key1 => [E1, E2, E3], key2 => [E1, E2, E3].为什么会这样?
即使这段代码有效,它看起来也很丑陋,特别是在减少我必须手动处理构建连接集合的逻辑的部分.有没有更好的方法呢?
谢谢!
我正在尝试使用groupingBy(...)lambda中的函数创建一个地图.现在我面临的问题是我无法将列表转换为特定条件的映射
码:
List<Integer> list = IntStream
.range(0,120)
.mapToObj(Integer::new)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
预期功能:
我需要收集一个地图,其键是键值,如0到120之间的键,值会增加
[]
[0]
[0, 1]
[0, 1, 2]
[0, 1, 2, 3]
[0, 1, 2, 3, 4]
[0, 1, 2, 3, 4, 5]
[0, 1, 2, 3, 4, 5, 6]
[0, 1, 2, 3, 4, 5, 6, 7]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
.
.
.
//so on upto 120
Map<Integer, List<Integer>> myMapOne = …Run Code Online (Sandbox Code Playgroud) 无法弄清楚如何读取特定建筑物列表中动物的平均体重。
我编写了另一种获取每种动物的动物名称的方法,所以我知道我的持久性正在起作用。
动物园:
public class Zoo {
private List<Animal> animals;
private List<Building> buildings;
public Zoo() {
this.animals = new PersistencyController().giveAnimals();
this.gebouwen = new PersistencyController().giveBuildings();
}
public List<Animal> giveAnimalsByKind(String kindName) {
return animals.stream().filter(animal -> animal.getKind().getName() == kindName).sorted(Comparator.comparing(Animal::getWeight)).collect(Collectors.toList());
}
public double giveAvgWeightForAnimalsInBuilding(String buildingName) {
return animals.stream().collect(Collectors.averagingDouble(Animal::getWeight));
}
}
Run Code Online (Sandbox Code Playgroud)
动物:
public class Animal implements Serializable {
private int nr;
private String name;
private double weight;
private Kind kind;
public Animal(int nr, String name, double weight, Kind kind) {
this.nr = nr;
this.name = …Run Code Online (Sandbox Code Playgroud) 我处于一种奇怪的情况下,其中有一个JSON API,该数组将以邻域字符串作为键的数组和以餐厅字符串作为值的数组,将GSON解析为Restaurant对象(String为邻域定义了A List<String>,餐馆)。系统将该数据存储在地图中,该地图的键是社区名称,值是该社区中的一组餐厅名称。因此,我想实现一个函数,该函数接收来自API的输入,按邻域对值进行分组,并连接餐馆列表。
受Java 8的约束,我无法使用更新的构造(例如flatMapping)在一行中完成所有操作,而我发现的最佳解决方案是此解决方案,该解决方案在连接这些列表之前使用中间映射存储一组List放入Set中以作为值存储在最终映射中:
public Map<String, Set<String>> parseApiEntriesIntoMap(List<Restaurant> restaurants) {
if(restaurants == null) {
return null;
}
Map<String, Set<String>> restaurantListByNeighborhood = new HashMap<>();
// Here we group by neighborhood and concatenate the list of restaurants into a set
Map<String, Set<List<String>>> map =
restaurants.stream().collect(groupingBy(Restaurant::getNeighborhood,
Collectors.mapping(Restaurant::getRestaurantList, toSet())));
map.forEach((n,r) -> restaurantListByNeighborhood.put(n, Sets.newHashSet(Iterables.concat(r))));
return restaurantListByNeighborhood;
}
Run Code Online (Sandbox Code Playgroud)
我觉得必须有一种方法可以摆脱该中间图,并一站式完成所有工作……某人是否有更好的解决方案可以让我做到这一点?