英文:
Java HashMap take out keys based on value
问题
这是我的哈希映射(Hashmap),其中键是一个名为Payment
的模型,值是一个String
,表示支付过程中发生的错误。
Map<Payment, String> mapPaymentWithError = new HashMap<>()
如果支付没有错误,我们将字符串值存储为null,并将Payment
模型数据作为键。
我正在尝试基于上述哈希映射中错误String
是否为Null
或NotNull
来对Payment
进行分组,该哈希映射包含许多记录。
如下所示:
List<Payment> withNullErrors = .............. // 具有null字符串值 List<Payment> withErrors = ................... // 具有NotNull字符串值
如何实现这一点?
尝试使用Collectors.GroupingBy
和其他方法,但未能成功。
英文:
This is my Hashmap in which the key is a model Payment
and value is a String
, which is an Error occurred during payment.
Map<Payment, String> mapPaymentWithError = new HashMap<>()
If there are no errors in Payment we are storing String value as null and the key as Payment model data.
I am trying to group Payment based on whether error String
was Null
or NotNull
from above HashMap which is having many records.
Like below
List<Payment> withNullErrors = .............. // having String value as Null
List<Payment> withErrors = ................... // having String value as NotNull
How to do this ?
Tried using Collectors.GroupingBy and other ways but its not working
答案1
得分: 1
以下是您要翻译的代码部分:
public class ListFiltering {
public static void main( String[] args ) {
Map<Payment, String> mapPaymentWithError = new HashMap<>();
mapPaymentWithError.put( new Payment( "1" ), "1" );
mapPaymentWithError.put( new Payment( "null" ), null );
List<Payment> withNullErrors = mapPaymentWithError.entrySet().stream()
.filter( e -> e.getValue() == null )
.map( e -> e.getKey() )
.toList();
List<Payment> withErrors = mapPaymentWithError.entrySet().stream()
.filter( e -> e.getValue() != null )
.map( e -> e.getKey() )
.toList();
System.out.println( "with null errors: " + withNullErrors );
System.out.println( "with other errors: " + withErrors );
}
static record Payment( String id ) {}
}
英文:
Do you mean something like this?
public class ListFiltering {
public static void main( String[] args ) {
Map<Payment, String> mapPaymentWithError = new HashMap<>();
mapPaymentWithError.put( new Payment( "1" ), "1" );
mapPaymentWithError.put( new Payment( "null" ), null );
List<Payment> withNullErrors = mapPaymentWithError.entrySet().stream()
.filter( e -> e.getValue() == null )
.map( e -> e.getKey() )
.toList();
List<Payment> withErrors = mapPaymentWithError.entrySet().stream()
.filter( e -> e.getValue() != null )
.map( e -> e.getKey() )
.toList();
System.out.println( "with null errors: " + withNullErrors );
System.out.println( "with other errors: " + withErrors );
}
static record Payment( String id ) {}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论