从Java中的列表获取最大值

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

Get Max Value from List in Java

问题

我有一个如下所示的列表

List{        
{Type=A, Amt=30000},{Type=A, Amt=50000},{Type=B, Amt=40000},{Type=B,Amt=60000},{Type=C,spRqstAmt=50000},{Type=C,Amt=10000}
}

我需要打印每种类型的最大金额。

输出:

类型:A,
金额:50000

类型:B,
金额:60000

类型:C,
金额:50000

如何实现这个目标?

英文:

I have a list like below

List{        
{Type=A, Amt=30000},{Type=A, Amt=50000},{Type=B, Amt=40000},{Type=B,Amt=60000},{Type=C,spRqstAmt=50000},{Type=C,Amt=10000}
}

I need to print the max amount for each Type.

Output:

Type: A,
Amt: 50000

Type: B,
Amt: 60000

Type: C,
Amt: 50000

How to achieve this?

答案1

得分: 2

请查看下面的代码。这应该适用于您。还可以有其他方法,这是使用HashMap的方法。

数据类

class Data{
    String type;
    int amt;
    
    Data(String s , int a){
        this.type = s;
        this.amt = a;
    }
}

实现类

Data data1 = new Data("A", 30000);
Data data2 = new Data("A", 50000);
Data data3 = new Data("B", 40000);
Data data4 = new Data("B", 60000);
Data data5 = new Data("C", 50000);
Data data6 = new Data("C", 10000);

ArrayList<Data> al = new ArrayList<>();
al.add(data1);
al.add(data2);
al.add(data3);
al.add(data4);
al.add(data5);
al.add(data6);

HashMap<String, Integer> hm = new HashMap<>();
for (int i = 0; i < al.size(); i++) {
    if (hm.containsKey(al.get(i).type)) {
        int tempAmt = hm.get(al.get(i).type);
        if (al.get(i).amt > tempAmt) {
            hm.put(al.get(i).type, al.get(i).amt);
        }
    } else {
        hm.put(al.get(i).type, al.get(i).amt);
    }
}

System.out.println(hm);
英文:

Check the below code . This should work for you . There could be other approaches also , this is using HashMap.

Data Class

class Data{
	String type;
	int amt;
	
	Data(String s , int a){
		this.type = s;
		this.amt = a;
	}
}

Implementation Class:

        Data data1 = new Data(&quot;A&quot;,30000);
		Data data2 = new Data(&quot;A&quot;,50000);
		Data data3 = new Data(&quot;B&quot;,40000);
		Data data4 = new Data(&quot;B&quot;,60000);
		Data data5 = new Data(&quot;C&quot;,50000);
		Data data6 = new Data(&quot;C&quot;,10000);
		
		ArrayList&lt;Data&gt; al = new ArrayList&lt;&gt;();
		al.add(data1);
		al.add(data2);
		al.add(data3);
		al.add(data4);
		al.add(data5);
		al.add(data6);
		
		
		
		HashMap&lt;String,Integer&gt; hm = new HashMap&lt;&gt;();
		for (int i = 0; i &lt; al.size(); i++) {
			if(hm.containsKey(al.get(i).type)) {
				int tempAmt = hm.get(al.get(i).type);
				if(al.get(i).amt &gt; tempAmt) {
					hm.put(al.get(i).type, al.get(i).amt);
				}
			}else {
				hm.put(al.get(i).type,al.get(i).amt);
			}
		}
		
		System.out.println(hm);

答案2

得分: 2

假设有一个类:

class DataClass {
  public String type;
  public Integer amt;
}

你可以这样做:

HashMap<String, Integer> values = new HashMap<>();
for (DataClass data : listDatas) {
  if (values.containsKey(data.type)) {
     int amt = values.get(data.type);
     if (data.amt > amt) {
       values.put(data.type, data.amt);
     }
  } else {
    values.put(data.type, data.amt);
  }
}

然后你可以打印结果。

英文:

Assuming a class:

class DataClass {
  public String type;
  public Integer amt;
}

You can:

HashMap&lt;String, Integer&gt; values = new HashMap&lt;&gt;();
for (DataClass data : listDatas) {
  if (values.contains(data.type)) {
     int amt = data.get(type);
     if (data.amt &gt; amt) {
       values.put(data.type, data.amt);
     }
  } else {
    values.put(data.type, data.amt);
  }
}

Then you can print the results.

答案3

得分: 0

使用toMap收集器将类型作为键,值冲突时以最大值为准,假设您的列表包含Element类型的对象:

Map<String, Integer> m = list.stream().collect(Collectors.toMap(Element::getType, Element::getAmt, Math::max))

(这是我临时想到的代码,我没有测试过)

英文:

Assuming your list contains objects of type Element, aggregate them using toMap collector into map where type is a key and value conflicts are resolved in favour of greatest value:

Map&lt;String,Integer&gt; m = list.stream().collect(Collectors.toMap(Element::getType, Element::getAmt, Math::max))

(code from top of my head, I didn't tested it)

答案4

得分: 0

与Tomáš Záluský的答案类似,使用流API的方式,但这样可以保留Element对象,如果以后需要它们:

import static java.util.Comparator.comparingInt;
import static java.util.function.BinaryOperator.maxBy;
import static java.util.stream.Collectors.toMap;

Map<String, Element> groupByMax = list.stream()
        .collect(toMap(Element::getType, e -> e, maxBy(comparingInt(Element::getAmt))));
Collection<Element> elementsWithMaxAmts = groupByMax.values();
英文:

Similar to the answer of Tomáš Záluský, using the stream API but this way you retain the Element objects, if you need them later:

import static java.util.Comparator.comparingInt;
import static java.util.function.BinaryOperator.maxBy;
import static java.util.stream.Collectors.toMap;

Map&lt;String, Element&gt; groupByMax = list.stream()
				.collect(toMap(Element::getType, e -&gt; e, maxBy(comparingInt(Element::getAmt))));
Collection&lt;Element&gt; elementsWithMaxAmts = groupByMax.values();

答案5

得分: 0

在这种情况下,没有真正的需要使用流。给出以下地图列表:

List<Map<String, String>> list =
    List.of(Map.of("Type", "A", "Amt", "30000"),
            Map.of("Type", "A", "Amt", "50000"),
            Map.of("Type", "B", "Amt", "40000"),
            Map.of("Type", "B", "Amt", "60000"),
            Map.of("Type", "C", "Amt", "50000"),
            Map.of("Type", "C", "Amt", "10000"));

您可以使用mapmerge方法来组合结果。

Map<String, String> results = new HashMap<>();

for (Map<String, String> m : list) {
    results.merge(m.get("Type"), m.get("Amt"),
            (a, b) -> Integer.valueOf(a)
                    .compareTo(Integer.valueOf(b)) == 1 ? a :
                            b);
}

results.entrySet().forEach(System.out::println);

打印出以下内容,显示具有最大金额的类型:

A=50000
B=60000
C=50000
英文:

There's no real need to use streams in this case. Give the following list of maps:

List&lt;Map&lt;String, String&gt;&gt; list =
		List.of(Map.of(&quot;Type&quot;, &quot;A&quot;, &quot;Amt&quot;, &quot;30000&quot;),
				Map.of(&quot;Type&quot;, &quot;A&quot;, &quot;Amt&quot;, &quot;50000&quot;),
				Map.of(&quot;Type&quot;, &quot;B&quot;, &quot;Amt&quot;, &quot;40000&quot;),
				Map.of(&quot;Type&quot;, &quot;B&quot;, &quot;Amt&quot;, &quot;60000&quot;),
				Map.of(&quot;Type&quot;, &quot;C&quot;, &quot;Amt&quot;, &quot;50000&quot;),
				Map.of(&quot;Type&quot;, &quot;C&quot;, &quot;Amt&quot;, &quot;10000&quot;));

You can use the merge method of map to combine the results.

Map&lt;String, String&gt; results = new HashMap&lt;&gt;();

for (Map&lt;String, String&gt; m : list) {
	results.merge(m.get(&quot;Type&quot;), m.get(&quot;Amt&quot;),
			(a, b) -&gt; Integer.valueOf(a)
					.compareTo(Integer.valueOf(b)) == 1 ? a :
							b);
	
}
results.entrySet().forEach(System.out::println);

Prints the following with the type showing the maximum amount.

A=50000
B=60000
C=50000

huangapple
  • 本文由 发表于 2020年8月8日 01:17:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63306502.html
匿名

发表评论

匿名网友

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

确定