标签: java-stream

Java中使用Stream合并两个排序数组

我有两个已排序的整数数组。我希望将它们合并到一个排序数组中。我想使用 Java Stream 来实现这一点。

我可以做一个嵌套流吗?

Arrays.asList(nums1).stream()
            .forEach(i -> Arrays.asList(nums2).stream()
                    .forEach(j -> //compare i,j)
                            .collect as list// ;  
Run Code Online (Sandbox Code Playgroud)

例如,[1,3,4]并且[2,5]应该返回[1,2,3,4,5]

java arrays sorting algorithm java-stream

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

从 List<Person> 中获取最年轻的 Person,其中 Person 的出生日期位于字符串 ISO8601 fromat 中

class Person {
    String name;
    String id;
    String dateOfBirth;
    int salary;
 }

 List <Person> listOfPersons; // Consider that list is filled with some data
Run Code Online (Sandbox Code Playgroud)

例如dateOfBirth = "2018-12-10T13:49:51.141Z";

出生日期采用 ISO8601 格式, 如果可以帮助对列表进行排序,则可以将其转换为java.util.Date with 。Date.from(Instant.parse(dateOfBirth));

那么,有什么方法可以使用 JAVA 8 中的流或不错的解决方案来从人员列表中获取最年轻的人员吗?

附加注释:Person 类不能更改。

java datetime java-stream

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

Java Stream - maxBy - 如何使用 Java 8 查找平均工资最高的部门

我有一份清单Employee。

public class Employee {
    private String department;
    private double salary;
    // other properties
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试查找平均工资最高的部门的名称。

我尝试过的代码:

List<Employee> employeeList = new ArrayList<Employee>();
employeeList.add(new Employee("abc", 38, "M", "QA", 115000.00d, 2016));
employeeList.add(new Employee("def", 23, "M", "Sports", 5000000.00d, 2011));
employeeList.add(new Employee("ghi", 38, "M", "QA", 120000.00d, 2007));
employeeList.add(new Employee("jkl", 35, "M", "DEV", 50000.00d, 2016));
employeeList.add(new Employee("mno", 30, "F", "QA", 80000.00d, 206));
employeeList.add(new Employee("pqr", 32, "F", "DEV", 75000.00d, 2014));

Map<String, Double> highestAvgSalary = employeeList.stream()
    .collect(Collectors.groupingBy(
        emp -> emp.getDepartment(),
        Collectors.averagingDouble(emp -> emp.getSalary(),                        
            Collectors.maxBy(Comparator.comparingDouble(emp -> …
Run Code Online (Sandbox Code Playgroud)

java java-stream collectors

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

如何使用java中的流对对象列表的多个字段求和

我试图从模型类中获取两个字段的总和。并使用 pojo 返回它,但不断出现语法错误。我想要实现的目标类似于此中得票最高的答案:使用流 API 对对象列表中的多个不同字段求和?但我遇到语法错误。这是我的模型:

public class BranchAccount {


    @NotNull(message = "Account balance is required")
    private Double accountBalance;

    @NotNull(message = "Profit is required")
    private Double profit;


    @Temporal(TemporalType.TIMESTAMP)
    private Date dateCreated;

    @Temporal(TemporalType.TIMESTAMP)
    private Date lastUpdated;
}
Run Code Online (Sandbox Code Playgroud)

我的波乔:

public class ProfitBalanceDto {

   private Double accountBalance;

   private Double profit;

}
Run Code Online (Sandbox Code Playgroud)

我从 BranchAccount 获取 accountBalance 和利润总和的代码:

public ProfitBalanceDto getAllBranchAccount() {
    List<BranchAccount> branchAccounts = branchAccountRepository.findAll();
            branchAccounts.stream()
            .reduce(new ProfitBalanceDto(0.0, 0.0), (branchAccount1, branchAccount2) -> {
                return new ProfitBalanceDto(
                        branchAccount1.getAccountBalance() + branchAccount2.getAccountBalance(),
                        branchAccount1.getProfit() + branchAccount2.getProfit());
            }); …
Run Code Online (Sandbox Code Playgroud)

java-8 spring-data-jpa spring-boot java-stream

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

验证 Java 中是否填充了所有字符串

我需要验证多个字符串并确保每个字符串都已填充或没有。

我正在接收数据,所以我无法控制它,并且未填充的可能是 null 或空字符串(只有空格的字符串被视为已填充)。

我显然可以写这样的东西:

String s1 = "A";
String s2 = "B";
String s3 = "C";

boolean valid = (
        (s1 == null || s1.isEmpty()) && 
        (s2 == null || s2.isEmpty()) && 
        (s3 == null || s3.isEmpty())
    ) || (
        (s1 != null && !s1.isEmpty()) && 
        (s2 != null && !s2.isEmpty()) && 
        (s3 != null && !s3.isEmpty())
);
Run Code Online (Sandbox Code Playgroud)

但这变得很难阅读,我认为最终我需要检查七个字符串。

所以我开始研究流,我可以做

boolean anyPopulated = Stream.of(s1, s2, s3).anyMatch(s -> s != null && !s.isEmpty());
boolean allPopulated = Stream.of(s1, s2, s3).allMatch(s -> …
Run Code Online (Sandbox Code Playgroud)

java validation boolean java-stream

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

展平映射 java 8 时,无法从静态上下文引用非静态方法

我有一个 Map<Integer、Map<String、List<String >>。我想将其展平为 Map<String, String> ,其中键是内部映射的键,值是使用 java 8 的内部映射列表的第一个元素。

这是我到目前为止所拥有的

public static void main(String[] args) {
    Map<Integer, Map<String, List<String>>> ip = new HashMap<>();
    Map<String, List<String>> iip1 = new HashMap<>();
    List<String> ilp1 = new ArrayList<>();
    ilp1.add("Uno");
    ilp1.add("Dos");
    ilp1.add("Tres");
    iip1.put("Alpha", ilp1);

    Map<String, List<String>> iip2 = new HashMap<>();
    List<String> ilp2 = new ArrayList<>();
    ilp2.add("One");
    ilp2.add("Two");
    ilp2.add("Three");
    iip2.put("Beta", ilp2);

    Map<String, List<String>> iip3 = new HashMap<>();
    List<String> ilp3 = new ArrayList<>();
    ilp3.add("Eins");
    ilp3.add("Zwei");
    ilp3.add("Drei");
    iip3.put("Gamma", ilp3);

    ip.put(1, iip1);
    ip.put(2, iip2);
    ip.put(3, iip3);
    
    
    Map<String, String> op …
Run Code Online (Sandbox Code Playgroud)

java collections hashmap java-8 java-stream

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

JAVA 对象列表与另一个列表要映射

给定一个类 Object1

class Object1 {
 private Object2 object2;
 private List<Object3> object3s;
}
Run Code Online (Sandbox Code Playgroud)

和一个List<Object1>

当前实施

Map<Object3, Object2> accountMap = new HashMap<>();
for (Object1 dto : accounts) {
            dto.getObject3s()
                    .forEach(dto -> accountMap.put(dto, dto.getObject2()));
        }
Run Code Online (Sandbox Code Playgroud)

如何Map<Object3, Object2>在流中创建preferred?

java hashmap java-stream collectors

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

使用 Java 流查找 Map 中的最大列表大小

我有一张表格的地图Map<String, List<Product>>。

我想在这个映射中找到具有最大关联列表的字符串。

我已经尝试了很多很多事情。最近:

map.entrySet()
.stream()
.max(Comparator((String entry1, String entry2) -> Integer.compare(q4().get(entry1).size(), q4.get(entry2).size()));
Run Code Online (Sandbox Code Playgroud)

没有任何效果。

java dictionary java-stream

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

使用 Java 流将列表转换为字符串

我创建了一个 for every 循环,并获得了价格代码列表,但我想在不使用任何循环的情况下获得相同的东西,并使用 java8 执行此操作供您参考,我发布了我的旧代码。我只想更改代码的这个位置。

List<ItemPriceCode> itemPriceCodes = item.getItemPriceCodes();
          List<String> priceCodeList = new ArrayList<String>();                              
          for (ItemPriceCode ipc : itemPriceCodes) {
              //get the string value from the list
               priceCodeList.add(ipc.getPriceCode());
        }
Run Code Online (Sandbox Code Playgroud)

但我不想使用任何循环我想在不使用任何循环的情况下获得相同的结果。为了解决这个问题,我尝试了这种方法,但没有取得任何成功。

itemPriceCodes.stream().map(n -> String.valueOf(n)).collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

这是我的这个函数的完整代码

private Item getItemManufacturerPriceCodes(Item item) {
          List<ItemPriceCode> itemPriceCodes = item.getItemPriceCodes();
          List<String> priceCodeList = new ArrayList<String>();
          for (ItemPriceCode ipc : itemPriceCodes) {
              //get the string value from the list
               priceCodeList.add(ipc.getPriceCode());
        }
          //pass this string value in query
          List<ManufacturerPriceCodes>mpc = manufacturerPriceCodesRepository.
                 findByManufacturerIDAndPriceCodeInAndRecordDeleted(item.getManufacturerID(),priceCodeList,NOT_DELETED);
          
          //Convert list to map
          Map<String, ManufacturerPriceCodes> …
Run Code Online (Sandbox Code Playgroud)

java java-8 java-stream

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

Java 列表、分区和获取排序中的最后一项

我有一个产品交易列表。我想找到 中每个产品的最终(最大)productTransactionId 销售List<ProductTransaction>。因此,我按 ProductId 对其进行分区,并按 ProductTransactionId 进行排序。下面示例中的最终列表List<Integer> (2, 5, 9) 如何做到这一点?我正在尝试使用流和过滤器。

@Data
public class ProductTransaction {
    private int productTransactionId;
    private int productId;
    private Date saleDate;
    private BigDecimal amount;
}
Run Code Online (Sandbox Code Playgroud)
产品交易ID 产品编号 发售日期 数量
1 1 2019年3月2日 5
2 1 2019 年 4 月 1 日 9
3 2 2019 年 4 月 1 日 2
4 2 2019年8月21日 3
5 2 2019年8月21日 4
6 3 2019年10月1日 2
7 3 2019年10月3日 5
8 3 2019年10月3日 7
9 3 …

java java-stream

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