我有一个自定义Foo对象列表,每个对象包含2个Cat和Dog对象列表,如下所示:
class Foo {
List<Cat> cats;
List<Dog> dogs;
}
class Cat {
int id;
}
class Dog {
String name;
}
Run Code Online (Sandbox Code Playgroud)
我有一个方法,我传入一个List请求,我想把它压平到一个Foo对象,其中包含每个请求狗和猫拼合在一起.有一个干净的紧凑方式吗?
来源清单:
List<Cat> catsForOne = new ArrayList<>(); // add a bunch of cats
List<Cat> catsForTwo = new ArrayList<>(); // add a bunch of cats
List<Dog> dogsForTwo = new ArrayList<>(); // add a bunch of dogs
List<Foo> requests = new ArrayList<>();
Foo one = Foo.builder().cats(catsForOne).build();
Foo two = Foo.builder().dogs(dogsForTwo).cats(catsForTwo).build();
requests.add(one);
requests.add(two);
Run Code Online (Sandbox Code Playgroud)
结果应该是:
Foo有一个List = catsForOne + catsForTwo和一个List = dogsForTwo
这是一个玩具示例,但你可以想象foo有大约5-6个集合(即Cat,Dog,Pig,Duck等),我想拥有一个Java …
我正在将我的应用程序从Joda-Time迁移到Java 8 java.time.
我遇到的一件事是使用图案中的模式打印基于周的一年DateTimeFormatter.
注意:我已经看到了这个问题: Java Time使用DateTimeFormatter解析基于星期的周模式
根据文件
y year-of-era year 2004; 04
Y week-based-year year 1996; 96
Run Code Online (Sandbox Code Playgroud)
然而,当我尝试这两个时,似乎Y总是和它一样y.
我的测试代码:
DateTimeFormatter yearF = DateTimeFormatter.ofPattern("yyyy").withZone(ZoneOffset.UTC);
DateTimeFormatter weekYearF = DateTimeFormatter.ofPattern("YYYY").withZone(ZoneOffset.UTC);
DateTimeFormatter dateTimeFormatter = new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR_OF_ERA) .appendLiteral(" ") .append(yearF)
.appendLiteral(" -- ")
.appendValue(IsoFields.WEEK_BASED_YEAR) .appendLiteral(" ") .append(weekYearF)
.toFormatter()
.withZone(ZoneOffset.UTC);
System.out.println(dateTimeFormatter.toString());
ZonedDateTime dateTime = ZonedDateTime.ofInstant(Instant.ofEpochMilli(946778645000L), ZoneOffset.UTC);
for (int i = 2000 ; i < 2020; i ++ ) {
System.out.println(dateTime.withYear(i).format(dateTimeFormatter));
}
Run Code Online (Sandbox Code Playgroud)
输出:
Value(YearOfEra)' '(Value(YearOfEra,4,19,EXCEEDS_PAD))' -- 'Value(WeekBasedYear)' '(Localized(WeekBasedYear,4,19,EXCEEDS_PAD)) …Run Code Online (Sandbox Code Playgroud) 我对spring和java 8更新鲜.我使用lambda表达式对列表进行了分组并得到了这种格式.
{
"2016": [
{"title":"Management","avg":0},
{"title":"Satisfaction","avg":0}
],
"2017": [
{"title":"aaa","avg":19},
{"title":"Energy","avg":6},
{"title":"energy","avg":17}
],
"2019": [
{"title":"Satisfaction","avg":0}
]
}
Run Code Online (Sandbox Code Playgroud)
我需要获得这种格式的所有数据
{"year":2016,"Management":0,"Satisfaction":0},
{"year":2017,"Stress":19,"Energy":6,"Workload":17},
{"year":2019,"Satisfaction":0}
Run Code Online (Sandbox Code Playgroud)
所以我写了一个java代码,
Map<String, Integer> mapNew = null;
for (Map.Entry<Integer, List<Tyma>> ee : mapList.entrySet()) { //looping the output of lambda expression
mapNew = new HashMap<String, Integer>();
mapNew.put("year",ee.getKey());
List<Tyma> li = ee.getValue();
for (Tyma dept : li) {
mapNew.put(dept.getTitle(), dept.getAvg()); //getters of Tyma class
}
}
Run Code Online (Sandbox Code Playgroud)
当我返回mapNew循环外部时,它仅返回最后一个数据({"year":2019,"Satisfaction":0}).但我需要获取所有数据.
我想,当我们放入mapNew = new HashMap<String, Integer>();父循环时,它将在每次迭代中创建新对象.
我尽力使用电子书和参考资料.如果有人解决它,请觉得有用.提前致谢.
我有一个Map对象Map<t1, Set<t2>>,我想进入集合并将t2集合转换为新地图的键.原始键t1将是地图的新值.
例如,给定一个包含两个条目的地图
{key1: [a, b, c], key2: [c, d]}
Run Code Online (Sandbox Code Playgroud)
得到的地图将是
{a: [key1], b: [key1], c: [key1, key2], d: [key2]}
Run Code Online (Sandbox Code Playgroud)
[]表示在上面的例子中设置.
我试图了解Java 8 Stream功能.
我想在特定目录路径的所有子目录中捕获数组中的所有文件(也可能是列表).
我的代码抛出了java.lang.ArrayStoreException错误
Run Code Online (Sandbox Code Playgroud)File[] files = Files.walk(Paths.get(path)) .filter(Files::isRegularFile) .toArray(File[]::new);
我尝试的另一件事是将文件名添加到现有的ArrayList:
Run Code Online (Sandbox Code Playgroud)ArrayList<String> existingNames = new ArrayList<String>(); Files.walk(Paths.get(path)) .filter(Files::isRegularFile) .forEach(p -> existingNames.add(p.getFileName()));
这也会抛出java.lang.ArrayStoreException错误.
我用同样的结果尝试的其他东西是:
Run Code Online (Sandbox Code Playgroud)File[] files = Files.walk(Paths.get(path)) .filter(Files::isRegularFile) .toArray(File[]::new);
谁能指出我正确的方向?
完整的堆栈跟踪是:
java.util.stream.Nodes的java.util.stream.SpinedBuffer.copyInto(SpinedBuffer.java:198)java.lang.System.arraycopy(Native Method)中的线程"main"java.lang.ArrayStoreException中的异常$ SpinedNodeBuilder .copyInto(Nodes.java:1290)位于java.util.stream上的java.util.stream.R井(SpinedBuffer.java:215)和java.util的$ SpinedNodeBuilder.asArray(Nodes.java:1296).在nachbearbeitung.CheckExistingMAIDs.main(CheckExistingMAIDs.java:41)的stream.ReferencePipeline.toArray(ReferencePipeline.java:439)
提前致谢!
我不明白之间的区别
this::myMethod
Run Code Online (Sandbox Code Playgroud)
和
ClassName::myMethod
Run Code Online (Sandbox Code Playgroud)
当这是ClassName类的实例时.
我认为在这两种情况下我都会调用该方法myMethod并将myObject其作为myMethod方法的参数运行,但我认为存在差异.它是什么?
我正在尝试编写以下代码,其中C是子类B.并且getValue方法仅在C,而不是在B.但Eclipse在此声明中显示错误:
Optional.ofNullable(A).map(A::getB).map(C::getValue);
Run Code Online (Sandbox Code Playgroud)
如果是正常情况,我们将输入类似的转换和写入((C)a.getB()).getValue().我怎么写一个相同的Optional?
学生和课程有两个普通对象,如下所示:
public class Student {
List<Course> courses;
...
}
public class Course {
String name;
...
}
Run Code Online (Sandbox Code Playgroud)
如果我们有一个list的Students,我们怎么能由他们的课程名称进行筛选一些学生的?
flatMap回答这个问题,但它返回课程对象而不是学生对象.allMatch(以下代码).但它会返回学生列表,但List始终为空.问题是什么?List<Student> studentList;
List<Student> AlgorithmsCourserStudentList = studentList.stream().
filter(a -> a.stream().allMatch(c -> c.getCourseName.equal("Algorithms"))).
collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud) Map<A, List<B>> xFunction() {
Map<A, List<B>> mapList = new HashMap<>();
List<A> aList = x.getAList();
for (A a : aList) {
List<B> bList = getBList(a.getId());
mapList.put(a, bList);
}
return mapList;
}
Run Code Online (Sandbox Code Playgroud)
如何在java 8中使用collect和grouping或映射转换它?
我试着用这样的东西:
x.getAList
.stream()
.map(a -> getBList(a.getId)) //return a list of B
.collect(Collectors.groupingBy (...) )
Run Code Online (Sandbox Code Playgroud)
干杯
我可以使用Java8提取特定部分,如下所示
request.getBody()
.getSections()
.filter(section -> "name".equals(section.getName))
.findFirst();
Run Code Online (Sandbox Code Playgroud)
但是如何在一行中使用可选项来做同样的事情.我的身体或部分可能为空.
我尝试了以下但没有工作
Optional.ofNullable(request)
.map(Request::getBody)
.map(Body::getSections)
.filter(section -> "name".equals(section.getName)) //compliation error. section is coming as a list here
.findFirst();
Run Code Online (Sandbox Code Playgroud)
我无法让这个工作在一条线上.我试过做flatMap但不能正常工作.请告知我们是否可以在单线上实现这一目标.
以下是完整的架构供参考
class Request {
Body body;
public Body getBody() {
return body;
}
public void setBody(Body body) {
this.body = body;
}
}
class Body {
List<Section> sections;
public List<Section> getSections() {
return sections;
}
public void setSections(List<Section> sections) {
this.sections = sections;
}
}
class Section {
private String name;
public …Run Code Online (Sandbox Code Playgroud) java-8 ×10
java ×9
java-stream ×4
optional ×2
collections ×1
datetime ×1
dayofweek ×1
java-time ×1
lambda ×1
spring ×1
spring-boot ×1
spring-mvc ×1