我想在遍历列表使用lambda时得到索引.
例如:
List<CheckBox> checkBoxes = null;
checkBoxes.forEach(checkBox -> {
if (checkBox.isSelected()) {
sb.append("index"); //I want to get checkbox index here
sb.append(",");
}
});
Run Code Online (Sandbox Code Playgroud)
编辑:这checkBoxes = null;只是一个占位符,但一旦我开始编写代码就会正常使用.
是否有一种更优雅的方式来加入流的元素,用"\n"分隔每个元素,但不以"\n"开头,而不必像下面的例子那样进行子串(1)调用?
List<String> strings = someList;
String rval = strings.stream()
.map(this::someOperation)
.reduce("", (p1, p2) -> p1 + "\n" + p2);
if(rval.length() > 0)
{
// trim off the leading "\n"
rval = rval.substring(1);
}
return rval;
}
Run Code Online (Sandbox Code Playgroud)
当然我可以用内部循环替换它,但这会失去明显的功能可读性
我已经将2D int数组转换为Stream:
IntStream dataStream = Arrays.stream(data).flatMapToInt(x -> Arrays.stream(x));
Run Code Online (Sandbox Code Playgroud)
现在,我想按升序对列表进行排序.我试过这个:
dataStream.sorted().collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
我对此感到困惑,因为在我看到的例子中,类似的事情没有错误.
我有一个Invoice对象列表,其中包含属性频率和数量(BigDecimal).
1)需要在不考虑精度的情况下,根据频率乘以和改变量.在下面显示的代码中输出但是输出失去了一些精度.金额值应为100.
2)是否可以用Java 8流API替换发票列表中的金额值.尝试使用
invoiceList.forEach(s -> s.getAmount().multiply(new BigDecimal("10")));
Run Code Online (Sandbox Code Playgroud)
但是这不会取代对象中的金额值.在这种情况下无法弄清楚使用replaceAll,尝试下面的代码,但给出编译错误,
newList.replaceAll((v) -> v.getAmount().multiply(frequencyFactor.get(v.getFrequency())));
Run Code Online (Sandbox Code Playgroud)
整个主要课程如下.无法更改任何数据类型或设计.我必须从Web服务处理获取的列表.
public class InvoiceMain {
public static void main(String[] args) {
List<Invoice> invoiceList = Arrays.asList(new Invoice("Quarterly", new BigDecimal(300)), new Invoice("Annually", new BigDecimal(1200)));
Map<String, BigDecimal> frequencyFactor = new HashMap<>();
frequencyFactor.put("Annually", new BigDecimal(1.0 / 12));
frequencyFactor.put("Quarterly", new BigDecimal(1.0 / 3));
for (Invoice invoice : invoiceList) {
invoice.setAmount(invoice.getAmount().multiply(frequencyFactor.get(invoice.getFrequency())));
}
System.out.println(invoiceList);
}
}
class Invoice {
private String frequency;
private BigDecimal amount;
public Invoice(String frequency, BigDecimal amount) {
super();
this.frequency = frequency; …Run Code Online (Sandbox Code Playgroud) 我正从DB中检索大块数据并使用此数据将其写入其他位置.为了避免漫长的处理时间,我正在尝试使用并行流来编写它.
当我将其作为顺序流运行时,它可以完美地运行.但是,如果我将其更改为并行,则行为很奇怪:它会多次打印同一个对象(超过10个).
@PostConstruct
public void retrieveAllTypeRecords() throws SQLException {
logger.info("Retrieve batch of Type records.");
try {
Stream<TypeRecord> typeQueryAsStream = jdbcStream.getTypeQueryAsStream();
typeQueryAsStream.forEach((type) -> {
logger.info("Printing Type with field1: {} and field2: {}.", type.getField1(), type.getField2()); //the same object gets printed here multiple times
//write this object somewhere else
});
logger.info("Completed full retrieval of Type data.");
} catch (Exception e) {
logger.error("error: " + e);
}
}
public Stream<TypeRecord> getTypeQueryAsStream() throws SQLException {
String sql = typeRepository.getQueryAllTypesRecords(); //retrieves SQL query in String format …Run Code Online (Sandbox Code Playgroud) 我正在使用Java 8流。
当我使用分隔符将其添加到地图中时,会得到重复的键异常,但是使用标准的for循环不会引发异常。
// This works
Map<Integer, String> myMap = new HashMap<>();
for (Row row : result.result()) {
myMap.put(row.get(0, Integer.class), null);
}
// This throws exception
myMap = StreamSupport.stream(result.result().spliterator(), true)
.collect(Collectors.toMap(row -> row.get(0, Integer.class), row -> ""));
Run Code Online (Sandbox Code Playgroud)
如果有什么不同,则结果为Cassandra结果集,行为Cassandra行。
我有一个公司实体对象列表。
package com.raghu.example2;
public class CompanyEntity {
private String name;
private String locationName;
private String officeName;
private String buildingName;
public CompanyEntity(String name, String locationName, String officeName, String buildingName) {
super();
this.name = name;
this.locationName = locationName;
this.officeName = officeName;
this.buildingName = buildingName;
// System.out.println(this);
}
public String getName() {
return name;
}
public String getLocationName() {
return locationName;
}
public String getOfficeName() {
return officeName;
}
public String getBuildingName() {
return buildingName;
}
@Override
public String toString() {
StringBuilder builder …Run Code Online (Sandbox Code Playgroud) 我正在尝试编写一个过滤谓词,它将根据不同对象中保存的值过滤列表,但是我想要提取要比较的值的对象在执行比较时可用,而不是在定义谓词的时间.
这是一个SSCCE
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
public class StreamTest {
public static void main(String [] args){
DataContainer dc = new DataContainer();
Predicate<Integer> p = new Predicate<Integer>(){
@Override
public boolean test(Integer t) {
/********************************************/
return t > 6; // I need this to be t > the limitValue that is available when the predicate gets executed
/********************************************/
}
};
System.out.println(dc.numberOfValuesGreaterThan(p, new LimitValue(6)));
}
}
class DataContainer{
private List<Integer> l = Arrays.asList(new Integer[]{1,2,3,4,5,6,7,8,9,10});
public long numberOfValuesSatisfyingPredicate(Predicate predicate,LimitValue lv){
return l.stream() …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用IntStream来增加流外部的int值.此方法的目的是查找相同位置上是否存在不相等的字符.n和单词字符串的长度相同.
当我尝试在forEach范围内递增计数器时,它向我显示它应该是最终的或有效的最终.任何人都可以建议一个更好的方法来做这个或增加这个计数器的方法?
public boolean check(String n,String word){
int counter=0;
IntStream.range(0, n.length())
.forEach(z->{
if(n.charAt(z)!=word.charAt(z)){
counter++;
}
});
if(counter>1)
return false;
else
return true;
}
Run Code Online (Sandbox Code Playgroud) 我试图读取目录的所有子目录中的所有文件.我写了逻辑,但我做了一些稍微错误的事情,因为它在每个文件中读取两次.
为了测试我的实现,我创建了一个包含三个子目录的目录,每个子目录中包含10个文档.这应该是30份文件.
这是我正确阅读文档的测试代码:
String basePath = "src/test/resources/20NG";
Driver driver = new Driver();
List<Document> documents = driver.readInCorpus(basePath);
assertEquals(3 * 10, documents.size());
Run Code Online (Sandbox Code Playgroud)
哪里Driver#readInCorpus有以下代码:
public List<Document> readInCorpus(String directory)
{
try (Stream<Path> paths = Files.walk(Paths.get(directory)))
{
return paths
.filter(Files::isDirectory)
.map(this::readAllDocumentsInDirectory)
.flatMap(Collection::stream)
.collect(Collectors.toList());
}
catch (IOException e)
{
e.printStackTrace();
}
return Collections.emptyList();
}
private List<Document> readAllDocumentsInDirectory(Path path)
{
try (Stream<Path> paths = Files.walk(path))
{
return paths
.filter(Files::isRegularFile)
.map(this::readInDocumentFromFile)
.collect(Collectors.toList());
}
catch (IOException e)
{
e.printStackTrace();
}
return Collections.emptyList();
}
private Document readInDocumentFromFile(Path path) …Run Code Online (Sandbox Code Playgroud)