我写了下面的代码来检查某些情况。
/**
* Returns true if any of the dose detail is an x
* @return boolean
*/
public <DD extends BD<DI>, DI extends BI> boolean Y(final Collection<DD> dds) {
return dds.stream().anyMatch(dd -> dd.M().K());
}
Run Code Online (Sandbox Code Playgroud)
但是此方法有一些风险dds,为空。我需要返回false也是dd也为null。如何使用Java 8将此方法修改为null安全?
jsonarray对象包含50000个jsonObject。我需要处理此jsonObject来创建对象,然后将其添加到列表中。这要花费很多时间,所以我想使用并行流制作对象并更快地添加到列表中。
这是我要用并行循环替换的代码
// I want to insert object in this array
List<Curriculum> curriculamList = new ArrayList<>();
// This is the org.json array
JSONArray jsonarray = new JSONArray(content);
// This loop I want to replace
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
// Start of processing
Program program = programDAO.getProgramDetails(jsonobject.getInt("programId"));
Batch batch = batchDAO.getBatchDetails(jsonobject.getInt("batchId"), program);
if(batch.getBatchId() == 0)
continue;
Major major = majorDAO.getMajorDetails(jsonobject.getInt("majorId"));
Course course = courseDAO.getCourseDetails(jsonobject.getString("courseCode"));
if(course == null)
continue;
double credits = …Run Code Online (Sandbox Code Playgroud) 我已经将常规的for循环代码转换为java 8流。我尝试了一些,但是我仍然在学习并且用尽了所有想法,请提出想法。可以进一步简化吗?除了使用forEach之外,我无法进行太多更改。另外,为什么我必须将eid转换为getERecordFromId((String)eid)中的String
Stream <String>eIdsStream = getEidStream();
final HashSet<String> declinedRecords = new HashSet<>();
eIdsStream.forEach (eid -> {
ERecord eRecord = getERecordFromId((String)eid);
if(eRecord.getEHash() != null && Status.DECLINED == eRecord.getStatus()) {
declineRecords.add(eRecord.getEHash());
}
}
Run Code Online (Sandbox Code Playgroud) 我想创建一个克隆列表。我正在使用以下代码段,但是即使MyClass具有默认构造函数,我的IDE也会显示“无法解析构造函数”的编译错误。
List<MyClass> clonedList =
myClassList.stream().map(MyClass::new).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
我是流媒体新手,如果我的语法错误,请帮助我。
在Java 8中,docs用于distinct()中间操作状态
返回由该流的不同元素组成的流(根据> Object.equals(Object))。对于有序流,选择不同的元素是稳定的(对于重复的元素,该元素首先出现
但是它没有被调用
我的Item类中的Equals方法
@Override
public boolean equals(Object obj) {
System.out.println(this.name+"<->"+((Item)obj).name);
return this.name.equals(((Item)obj).name);
}
Run Code Online (Sandbox Code Playgroud)
在数据类中定义数据
public static List<Item> getItemList(){
itemData.add(new Item("Orange","Citrus Fruit","Orange",30,true,false));
itemData.add(new Item("Apple Green","Universal Fruit","Green",60,false,true));
itemData.add(new Item("Papaya","Wonderful Fruit","Yellow",120,false,true));
itemData.add(new Item("Papaya","Wonderful Fruit","Green",100,false,true));
.
.
.
itemData.add(new Item("Strawberry","Citrus Fruit","Red",25,true,false));
itemData.add(new Item("Sapota","Brown Fruit","Brown",32,false,true));
return itemData;
}
Run Code Online (Sandbox Code Playgroud)
使用流
Data.getItemList().stream().distinct().forEach(System.out::println)
Run Code Online (Sandbox Code Playgroud)
但我意识到equals方法没有被调用
我有这张地图:
Map<String, Map<String, String>> listMap = new HashMap<>();
Run Code Online (Sandbox Code Playgroud)
我想Keys从Mapmain中选择所有与之不同的值Map:listMap.value.key
List<String> distinct = listMap.entrySet().stream()
.map(e -> e.getValue()) //Map<String, String>
//Select key of value
.distinct().collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
我不知道如何选择key的value的listMap。
之前已经回答过类似的问题,但是我仍然无法弄清楚我的分组和平均方法有什么问题。
我曾尝试多个返回值的组合一样Map<Long, Double>,Map<Long, List<Double>,Map<Long, Map<Long, Double>>,Map<Long, Map<Long, List<Double>>>和那些没有修复错误的IntelliJ我抛出的:“非静态方法不能从静态上下文中引用”。此刻,我觉得我只是在盲目猜测。那么,谁能给我一些关于如何确定正确的回报类型的见解?谢谢!
方法:
public static <T> Map<Long, Double> findAverageInEpochGroup(List<Answer> values, ToIntFunction<? super T> fn) {
return values.stream()
.collect(Collectors.groupingBy(Answer::getCreation_date, Collectors.averagingInt(fn)));
}
Run Code Online (Sandbox Code Playgroud)
答案类别:
@Getter
@Setter
@Builder
public class Answer {
private int view_count;
private int answer_count;
private int score;
private long creation_date;
}
Run Code Online (Sandbox Code Playgroud) streamToArray以下代码需要做什么?
IntStream stream = IntStream.range(0, 3);
int[] array = streamToArray(stream); // array = [0, 1, 2]
Run Code Online (Sandbox Code Playgroud) 我试图用java lambda expresions替换现有的循环.
我有简单的数据结构,如下所示:
class DbObject{
private Long objectId;
private Long basedOnObjectId; //<- this field can be null
public Long getObjectId() {
return objectId;
}
public void setObjectId(Long objectId) {
this.objectId = objectId;
}
public Long getBasedOnObjectId() {
return basedOnObjectId;
}
public void setBasedOnObjectId(Long basedOnObjectId) {
this.basedOnObjectId = basedOnObjectId;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我有一个DbObjects列表
我尝试使用指定的basedOnObjectId过滤每个DbObject:
(1) list.stream().filter(object -> obejct.getBasedOnObjectId()
.equals(basedOnObject.getObjectId()))
.collect(Collector.of(List))
Run Code Online (Sandbox Code Playgroud)
当然这个代码给了我NullPointer,因为有些od DbObject没有BasedOnObjectId因为它们是根.
很自然的事情是替换字段"Long basedOnObjectId;" 通过可选,但正如我在开始时提到的那样,现有的生产代码是不是快速修复.
所以我试着做一些改变,我评估下面的句子:
Optional<Long> option = Optional.ofNullable(objectWithNullBasedOnId.getBasedOnObjectId());
Run Code Online (Sandbox Code Playgroud)
并尝试使用.get()方法或.ifPresent(),但.get()也会抛出空指针异常,ifPresent不专用于使用流.
我注意到这一事实,当我有DbObject with null basedOnObjectId时,我不必检查值是否完全为null但只跳过此执行步骤.
所以我决定使用.orElse()方法并返回一些假值.在这种情况下,我返回0L值,因为这个索引在DB中不存在:)
所以我的代码:
(2) List newList = …Run Code Online (Sandbox Code Playgroud) 需要逐行读取文本并根据对象Entity成员的值解析每个文本.我的实体有下一个构造函数签名:
public Entity(int id, String name, double weight)
Run Code Online (Sandbox Code Playgroud)
文本文件有下一个内容:
ID,NAME,WEIGHT
1,Mario,80.2
2,Marco,91.1
...
100,Diego,78.12
Run Code Online (Sandbox Code Playgroud)
使用新的Java 8:Files::readAllLines方法我的解决方案非常庞大:
public class CoolApp {
private static final String SOURCE_FILE = "path/to/txt/file/entities.txt";
private static final int ID = 0;
private static final int NAME = 1;
private static final int WEIGHT = 2;
public static void main(String[] args) throws Exception {
boolean isHeader = true;
List<Entity> entities = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get(SOURCE_FILE))) {
if (isHeader) {
isHeader = …Run Code Online (Sandbox Code Playgroud) java-stream ×10
java ×9
java-8 ×5
lambda ×4
collections ×2
arrays ×1
collectors ×1
io ×1
nio ×1