过滤一个列表,基于一些值,然后再根据第一个输出对结果进行过滤。

huangapple go评论66阅读模式
英文:

Filter a list based on some values and again filter the result on first output

问题

以下是翻译好的部分:

我目前有一个情况,我有一个列表,我根据其中的值进行过滤,然后根据结果再次进行过滤。

for (Employee emp : data.getEmployees()) {
    if (emp.getAge() > 30) {
        for (Position position : emp.getPositions()) {
            if (position.getName().equalsIgnoreCase("Manager")) {

                return position;
            }
        }
    }
}

如何在使用 Java 8 的流(Stream)呢?

data.getEmployees().stream().filter(emp -> emp.getAge() > 30) 

不确定如何进一步使用。因为这只会得到员工列表,我只想要职位是经理的员工列表。

英文:

I currently have a scenario where I have a List and I filter based on the values inside this and I need to filter again based on the outcome.

for (Employee emp : data.getEmployees()) {
	if (emp.getAge() > 30) {
		for (Position position : emp.getPositions()) {
			if (position.getName().equalsIgnoreCase("Manager")) {

				return position;
			}
		}
	}
}

How to use it using Java 8 stream?

data.getEmployees().stream().filter(emp -> emp.getAge>30) 

Not sure on how to use it further. As this will just result in the list of employees I just want the list of employee with position as manager

答案1

得分: 3

我假设您要获取“Position”或这些的流:

data.getEmployees().stream()
    .filter(emp -> emp.getAge > 30)
    .flatMap(emp -> emp.getPositions().stream())
    .filter(pos -> "Manager".equalsIgnoreCase(pos.getName()))

flatMap 创建一个包含由参数中的所有元素的流的所有元素的新流。

或者要获取所有的经理员工:

data.getEmployees().stream()
    .filter(emp -> emp.getAge > 30)
    .filter(emp -> emp.getPositions().stream().anyMatch(pos ->
        "Manager".equalsIgnoreCase(pos.getName())
    ))

它只是创建了所有员工的职位的新流,并测试是否有一个职位名称为 Manager

如果您想将其作为列表获取,只需添加 .collect(Collectors.toList())

英文:

I assume you want to either get the Positions or a stream of those:

data.getEmployees().stream()
.filter(emp -> emp.getAge>30)
.flatMap(emp->emp.getPositions().stream())
.filter(pos->"Manager". equalsIgnoreCase (pos.getName()))

flatMap creates a new stream containing all elements of the streams found by the parameter of all elements.

Or to get all employees that are managers:

data.getEmployees().stream()
.filter(emp -> emp.getAge>30)
.filter(emp->emp.getPositions().stream().anyMatch(pos->
    "Manager". equalsIgnoreCase (pos.getName())
))

It just creates a new stream of the positions of all employees and tests if there is one with the name Manager.

If you want to e.g. get it as list, you can just append .collect(Collectors.toList()).

huangapple
  • 本文由 发表于 2020年9月14日 17:49:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/63881953.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定