标签: java-stream

如何将 LocalDateTime yyyy-MM-dd HH:mm 格式化为 dd-MM-yyyy HH:mm 作为字符串,以获取不仅包含日期属性的对象的整个列表?

我正在尝试解决一个似乎很棘手但我陷入困境的问题。你能帮忙吗?

在 Spring Boot 中,我有一个Holiday保存在 MySQL 数据库上的国定假日对象。该对象Holiday包含以下属性:

(...)

@Column(name = "title")
private String HolidayTitle;

@Column(name = "date")
private String holidayDate;

@Column(name = "updated")
private LocalDateTime updated;

@Column(name = "country")
private String country;

(...)
Run Code Online (Sandbox Code Playgroud)

但我对该属性感兴趣updated,该属性在数据库中存储为 2021-10-26 20:54:48。我想将其格式化为 Thymeleaf 的 dd-MM-yyyy HH:mm,但它由具有不同属性的对象列表组成Holiday

在控制器中,列表被检索如下:

@GetMapping("/getAllHolidays")
public String getAllHolidays(Model theModel) {
    List<Holiday> theHolidays = holidayService.findAll();
    theModel.addAttribute("holidays", theHolidays);
    return "holidays";
}
Run Code Online (Sandbox Code Playgroud)

如何使用仅格式化updated列表中所有假日对象的属性?theHolidaysDateTimeFormatter

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm");
Run Code Online (Sandbox Code Playgroud)

是否可以使用Java流来实现这一点?

java date spring-boot java-stream datetimeformatter

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

java 8 流的内部迭代是什么样子的

我试图理解外部迭代器与内部迭代器之间的区别,其中外部迭代器使用迭代器来枚举其元素

List<String> alphabets = Arrays.asList(new String[]{"a","b","b","d"});
         
for(String letter: alphabets){
   System.out.println(letter.toUpperCase());
}
Run Code Online (Sandbox Code Playgroud)

上面的后台代码做了类似下面的事情

List<String> alphabets = Arrays.asList(new String[]{"a","b","b","d"});    
Iterator<String> iterator = alphabets.listIterator();
while(iterator.hasNext()){
     System.out.println(iterator.next().toUpperCase());
}
Run Code Online (Sandbox Code Playgroud)

但对于内部迭代,一切都是在后台完成的,这对我来说是一个黑匣子,我想深入研究它。

就像下面的代码一样,迭代是在后台发生的,但到底发生了什么以及与 foreach 循环相比有何不同?

List<String> alphabets = Arrays.asList(new String[]{"a","b","b","d"});
alphabets.stream().forEach(l -> l.toUpperCase());
Run Code Online (Sandbox Code Playgroud)

这是我对外部迭代和内部迭代的理解。如果我错了,请纠正我。

java java-8 java-stream

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

如果使用java流列表中的一个变量为假,如何删除对象

我正在使用 java 8
我有一个像这样的模型类

class Student{
    String name;
    List<Subject> subjects1;
    List<Subject> subjects2;
    List<Subject> subjects3;
    // getters & setters
}

class Subject{
    String sub;
    Integer marks;
    boolean status;
    // getters & setters
}
Run Code Online (Sandbox Code Playgroud)

status可能是真的,也可能是假的。
现在,如果状态为 false,那么我必须从主题列表中删除这些对象
如何在 Streams 中执行此操作?
提前致谢。

java java-stream

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

如何在Java中将Map中的key * value相乘?

我有这门课:

\n
class Product {\n    public double price;\n\n    public Product(double price) {\n        this.price = price;\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

还有一张地图:

\n
Map<Product, Integer> products = new HashMap<>();\n
Run Code Online (Sandbox Code Playgroud)\n

其中包含添加的几种产品,如下所示:

\n
products.put(new Product(2.99), 2);\nproducts.put(new Product(1.99), 4);\n
Run Code Online (Sandbox Code Playgroud)\n

我想使用流计算所有乘积的总和乘以值?我试过:

\n
double total = products.entrySet().stream().mapToDouble((k, v) -> k.getKey().price * v.getValue()).sum();\n
Run Code Online (Sandbox Code Playgroud)\n

但它无法编译,我得到 \xe2\x80\x9c无法解析方法getValue()\xe2\x80\x9d。

\n

我预计:

\n
(2.99 * 2) + (1.99 * 4) = 5.98 + 7.96 = 13.94\n
Run Code Online (Sandbox Code Playgroud)\n

java java-8 java-stream

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

如何获取具有最小属性的列表元素?

我编写这段代码来找到最年轻的人:

import java.util.Comparator;
import java.util.List;

public class PersonImpl implements PersonInterface {

    @Override
    public Person youngest(List<Person> personList) {
        Integer minAge = personList.stream()
                .map(Person::getAge)
                .min(Comparator.comparing(Integer::valueOf))
                .orElse(null);
        return personList.stream()
                .filter(person -> person.getAge() == minAge)
                .toList()
                .stream()
                .findFirst()
                .orElse(null);
    }
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我做到了并且工作正常。现在我想知道我是否可以以更好的方式做到这一点(也许不是只对一个执行 2 个“语句”?) PS:我只提供了代码,因为我认为不需要发布所有的这里的其他课程只是为了回顾这一课程。

有人可以解释一下如何才能拥有更好的代码(更少的行)吗?谢谢

java java-stream java-17

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

Java流方法如何运行?

我刚刚了解Java流。可以通过在 Collection 上调用 .stream() 来创建流,然后您可以使用docs中描述的方法对该流进行操作。

我不明白的是这个过程实际发生在哪里。我的意思是我可以创建一个具有年龄属性的 Person 对象流并按如下方式对其进行排序:

Person john = new Person(30);
Person anne = new Person(25);
Person bill = new Person(52);

ArrayList<Person> people = new ArrayList<Person>();
people.add(john);
people.add(anne);
people.add(bill);

ArrayList<Person> sortedPeople = people
.stream()
.sorted(Comparators.comparing(person -> person.getAge()))
.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
Run Code Online (Sandbox Code Playgroud)

但在我发现的文档和源代码中,函数式接口(例如包含排序方法的函数式接口)没有排序代码,仅描述传递给它的 lambda 函数。我在这里严重误解了什么吗?

java java-stream

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

将带有 return 语句的 for 循环转换为流并过滤 lambda 语句

如何将下面带有 return 语句的 for 循环转换为 lambda 表达式或带有过滤器的流。

for(PhysicianData d : physicianDataList)
    {
        if(d.getPhysicianName().equals(physicianName))
        {
            return true;
        }
    }
Run Code Online (Sandbox Code Playgroud)

java java-8 java-stream

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

如何使用 Stream API 从列表中获取具有最高值的 3 个对象

我有一个这样的方法:

public String mostExpensiveItems() {
        List<Entry> myList = getList();
        List<Double> expensive = myList.stream()
                .map(Entry::getAmount)
                .sorted(Comparator.reverseOrder())
                .limit(3)
                .toList();

        return "";
    }
Run Code Online (Sandbox Code Playgroud)

此方法需要以字符串形式返回最昂贵商品的产品 ID ,如下所示:3

"item1, item2, item3"
Run Code Online (Sandbox Code Playgroud)

我应该只能使用流,但我被困在这里了。我应该能够按值对项目进行排序,然后获取产品 ID,但我似乎无法使其工作。

入门级

public class Entry {

    private String productId;
    private LocalDate date;
    private String state;
    private String category;
    private Double amount;

    public Entry(LocalDate orderDate, String state, String productId, String category, Double sales) {
        this.date = orderDate;
        this.productId = productId;
        this.state = state;
        this.category = category;
        this.amount = sales;
    }

    public String …
Run Code Online (Sandbox Code Playgroud)

java sorting list java-stream

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

Java stream API to find length of each string in list

I have a String array in java as follows.

String[] text = {"hello", "bye"};
Run Code Online (Sandbox Code Playgroud)

Now I need to use Java stream API to calculate the length of each string in this array. I do not want to use for loop. How can I do that?

Update: I have checked this link and got the following code to get the sum of the length of each string of this array.

Arrays.stream(text)
      .filter(Objects::nonNull)
      .mapToInt(String::length)
      .reduce(0,Integer::sum);
Run Code Online (Sandbox Code Playgroud)

java arrays string java-stream

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

在 Map&lt;String, List&lt;Integer&gt;&gt; 中查找最大值的最小值,而不依赖于 for 循环

我有一张 类型的地图HashMap<String, List<Integer>>

我想找到每个地图条目的最大值,然后找到这些最大值中的最小值

我知道这可以使用几个 for 循环来完成。但想知道是否有另一种方法可以做到这一点(也许使用流?)

我要寻找的最终结果是一个整数。

例子:

HashMap<String, List<Integer>> values = new HashMap<>();

values.put("a", Arrays.asList(4, 8, 9, 10)); // max value is 10
values.put("b", Arrays.asList(20, 32, 1, 2)); // max value is 32
values.put("c", Arrays.asList(11, 50, 20, 6)); // max value is 50

// I need the min value out of the above maximums i.e. 10 (final answer)
Run Code Online (Sandbox Code Playgroud)

java hashmap java-stream

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