使用 Java 中的 Lambda 表达式打印字符串的最后一个数字。

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

Need to print last digit of string using lambda expression using java

问题

public static void main(String[] args) {
    List<TestDTO> studs = new ArrayList<>();
    studs.add(new TestDTO("101", "Test 101"));
    studs.add(new TestDTO("102", "Test 102"));

    Map<String, TestDTO> mapDbCardDtl = studs.stream().collect(Collectors.toMap(TestDTO::getId, Function.identity()));

    Set<String> s = mapDbCardDtl.keySet();
    System.out.println("s: " + s.toString());
}
public class TestDTO {
    String id;
    String name;

    public TestDTO(String id, String name) {
        super();
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Output from the above code:

s: [101, 102]

The expected output:

S : [1, 2]
英文:

I want to print the last digit from a string using a lambda expression. Using the below code I was able to print a complete number I but want to print the last digit

public static void main(String[] args) {
		List&lt;TestDTO&gt; studs = new ArrayList&lt;&gt;();
		studs.add(new TestDTO(&quot;101&quot;, &quot;Test 101&quot;));
		studs.add(new TestDTO(&quot;102&quot;, &quot;Test 102&quot;));

		Map&lt;String, TestDTO&gt; mapDbCardDtl = studs.stream().collect(Collectors.toMap(TestDTO::getId, Function.identity()));

		Set&lt;String&gt; s = mapDbCardDtl.keySet();
		System.out.println(&quot;s: &quot; + s.toString());
	}

Below is the DTO

public class TestDTO {
	String id;
	String name;

	public TestDTO(String id, String name) {
		super();
		this.id = id;
		this.name = name;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

Output from the above code:

s: [101, 102]

The expected output:

S : [1, 2]

答案1

得分: 1

如果您只对从ID中打印出最后一个数字感兴趣,而该数字是以字符串形式编写的,请参考以下代码:

List<String> s = studs.stream()
    .map(dto -> dto.getId())
    .map(id -> String.valueOf(id.charAt(id.length() - 1))) // 取最后一个字符并转换为字符串
    .collect(Collectors.toList());

如果您想要从名称值中获取最后一个数字:

final Pattern numberPattern = Pattern.compile(".*([0-9]+).*$");
List<String> s = studs.stream()
    // 在名称中查找数字
    .map(dto -> numberPattern.matcher(dto.getName()))
    .filter(Matcher::matches)
    .map(matcher -> matcher.group(1))
    // 找到最后一个数字
    .map(lastNumber -> String.valueOf(lastNumber.charAt(lastNumber.length() - 1)))
    .collect(Collectors.toList());

提示:

如果您希望mapDbCardDtl的键具有最后一个数字,则当多个数字以相同数字结尾时可能会失败。您将需要在toMap收集器中使用覆盖合并函数。

public static <T, K, U>
    Collector<T, ?, Map<K, U>> toMap(Function<? super T, ? extends K> keyMapper,
                                     Function<? super T, ? extends U> valueMapper,
                                     BinaryOperator<U> mergeFunction)

第二个解决方案是使用groupBy方法,将TestDTO聚合成Map<String, List<TestDTO>>。这里的键是您的数字,值是具有该数字的Dto的列表。

英文:

If you are interested only in printing last number from the id, which is a number written as String, then:

 List&lt;String&gt; s = studs.stream()
            .map(dto-&gt;dto.getId())
            .map(id -&gt; String.valueOf(id.charAt(id.length() - 1))) // take last character and cast to String
            .collect(Collectors.toList()); 

If you want to get. last digit from name value:

 final Pattern numberPattern = Pattern.compile(&quot;.*([0-9]+).*$&quot;);
 List&lt;String&gt; s = studs.stream()
            // find nunmber in name
            .map(dto -&gt; numberPattern.matcher(dto.getName()))
            .filter(Matcher::matches)
            .map(matcher -&gt; matcher.group(1))
             // find last digit
            .map(lastNumber -&gt;String.valueOf(lastNumber.charAt(lastNumber.length()-1)))
            .collect(Collectors.toList());

TIP:

If you wanted mapDbCardDtl to have last digit as the key, then you may fail, when more than one number ends with same digit. You will have to use overwrite merge function in toMap collector.

public static &lt;T, K, U&gt;
    Collector&lt;T, ?, Map&lt;K,U&gt;&gt; toMap(Function&lt;? super T, ? extends K&gt; keyMapper,
                                    Function&lt;? super T, ? extends U&gt; valueMapper,
                                    BinaryOperator&lt;U&gt; mergeFunction)

Second solution would be using groupBy method, that will aggregate TestDTO into Map&lt;String,List&lt; TestDTO &gt;&gt;. Here the key is your digit and value : list of Dto's with this digit.

答案2

得分: 1

你可以将学生对象转换为 id 的最后一位数字,然后收集到一个列表中。

List<String> lastDigits = 
         studs.stream()
              .map(s -> s.getId().substring(s.getId().length() - 1)))
              .collect(Collectors.toList());

注意:如果你将其收集到 Set 中,那么它将只包含唯一的数字。

英文:

You can transform your Student's object into the last digit of id then collect in a list.

List&lt;String&gt; lastDigits = 
         studs.stream()
              .map(s -&gt; s.getId().substring(s.getId().length() - 1)))
              .collect(Collectors.toList());

Note: If you collect in Set then it will contain only unique digits.

答案3

得分: 1

你不能使用Funcion#identity并期望拥有具有修改值的不同实体。一种方法是将Map<String, TestDTO>转换为Map<String, String>并使用以下代码:

Map<String, String> mapDbCardDtl = studs
                                  .stream()
                                  .collect(Collectors.toMap(TestDTO::getId, 
                                  (testDto) -> String.valueOf(testDto.getId().charAt(testDto.getId().length() - 1))));

Set<String> s = mapDbCardDtl.keySet();
System.out.println("s: " + s.toString());
英文:

You can't use Funcion#identity and expect to have different entity with modified values. One way is to convert Map&lt;String, TestDTO&gt; to Map&lt;String, String&gt; and use the following code:

Map&lt;String, String&gt; mapDbCardDtl = studs
                                      .stream()
                                      .collect(Collectors.toMap(TestDTO::getId, 
                                      (testDto) -&gt; String.valueOf(testDto.getId().charAt(testDto.getId().length() - 1))));

Set&lt;String&gt; s = mapDbCardDtl.keySet();
System.out.println(&quot;s: &quot; + s.toString());

答案4

得分: 1

如果您只想要打印出键的最后一个字符,在 println 语句之前添加以下行:

s = s.stream().map(x -> x.substring(x.length() - 1)).collect(Collectors.toSet());

如果您实际上希望映射中的键仅为最后一个字符,请将流逻辑更改为:

Map<String, TestDTO> mapDbCardDtl = studs.stream()
		.collect(Collectors.toMap(t -> t.getId().substring(t.getId().length() - 1), Function.identity()));
英文:

If you simply want to print the last character of the keys, add this line right before the println statement:

s = s.stream().map(x -&gt; x.substring(x.length() - 1)).collect(Collectors.toSet());

If you actually wanted the keys in the map to only be the last character, change the stream logic to:

Map&lt;String, TestDTO&gt; mapDbCardDtl = studs.stream()
		.collect(Collectors.toMap(t -&gt; t.getId().substring(t.getId().length() - 1), Function.identity()));

答案5

得分: 0

  1. 你已经完成了大部分,只需要进行一些集合操作即可。
  2. 看一下我在主方法中所做的编辑,它会打印出你想要的结果。
public static void main(String[] args) {
    List<TestDTO> studs = new ArrayList<>();
    studs.add(new TestDTO("101", "Test 101"));
    studs.add(new TestDTO("102", "Test 102"));

    Map<String, TestDTO> mapDbCardDtl = studs.stream().collect(Collectors.toMap(TestDTO::getId, Function.identity()));

    Set<String> s = mapDbCardDtl.keySet().stream()
            .map(number -> String.valueOf(number.charAt(number.length() - 1))) // 取最后一个字符并转换为字符串
            .collect(Collectors.toSet());
    System.out.println("s: " + s);
}
英文:
  1. You have already done the most part of it, Just a little set manipulation was needed.

  2. Look at the edit I made in the main method it will print your desire result.

      public static void main(String[] args) {
         List&lt;TestDTO&gt; studs = new ArrayList&lt;&gt;();
         studs.add(new TestDTO(&quot;101&quot;, &quot;Test 101&quot;));
         studs.add(new TestDTO(&quot;102&quot;, &quot;Test 102&quot;));
    
         Map&lt;String, TestDTO&gt; mapDbCardDtl = studs.stream().collect(Collectors.toMap(TestDTO::getId, Function.identity()));
    
         Set&lt;String&gt; s = mapDbCardDtl.keySet().stream()
                 .map(number -&gt; String.valueOf(number.charAt(number.length() - 1))) // take last character and cast to String
                 .collect(Collectors.toSet());;
         System.out.println(&quot;s: &quot; + s);
     }
    

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

发表评论

匿名网友

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

确定