标签: java-stream

如何在使用流遍历列表时获取元素索引?

我想在遍历列表使用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;只是一个占位符,但一旦我开始编写代码就会正常使用.

java lambda android java-8 java-stream

2
推荐指数
1
解决办法
8133
查看次数

在stream.reduce之后是否有更优雅的方法来切断主角?

是否有一种更优雅的方式来加入流的元素,用"\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)

当然我可以用内部循环替换它,但这会失去明显的功能可读性

reduce java-8 java-stream

2
推荐指数
2
解决办法
54
查看次数

如何按升序对IntStream进行排序?

我已经将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)

但我得到编译时错误 错误

我对此感到困惑,因为在我看到的例子中,类似的事情没有错误.

java sorting java-stream

2
推荐指数
1
解决办法
533
查看次数

使用java 8划分对象列表中的bigdecimal值?

我有一个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)

java lambda java-8 java-stream

2
推荐指数
1
解决办法
647
查看次数

并行流重复项目

我正从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 java-stream

2
推荐指数
1
解决办法
298
查看次数

分离器导致重复键异常,而for循环不

我正在使用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行。

java cassandra java-8 java-stream

2
推荐指数
1
解决办法
64
查看次数

Java 8 Lambda表达式中的分组依据

我有一个公司实体对象列表。

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)

lambda java-8 java-stream

2
推荐指数
1
解决办法
2791
查看次数

编写一个Java 8谓词,根据不在范围内的值进行过滤

我正在尝试编写一个过滤谓词,它将根据不同对象中保存的值过滤列表,但是我想要提取要比较的值的对象在执行比较时可用,而不是在定义谓词的时间.

这是一个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)

java java-8 java-stream

2
推荐指数
2
解决办法
477
查看次数

递增IntStream外部的整数值

我正在尝试使用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)

java java-8 java-stream

2
推荐指数
2
解决办法
459
查看次数

如何使用Files.walk读取子目录中的所有文件一次?

我试图读取目录的所有子目录中的所有文件.我写了逻辑,但我做了一些稍微错误的事情,因为它在每个文件中读取两次.

为了测试我的实现,我创建了一个包含三个子目录的目录,每个子目录中包含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)

java file-io java-8 java-stream

2
推荐指数
1
解决办法
1097
查看次数

标签 统计

java-stream ×10

java-8 ×9

java ×7

lambda ×3

android ×1

cassandra ×1

file-io ×1

reduce ×1

sorting ×1